<?php

include_once __DIR__ . '/secrets.php';
include 'db_connect.php';

$userid   = $_POST['userid'] ?? null;
$image    = $_POST['image'] ?? null;
$type     = $_POST['type'] ?? null;
$key      = $_POST['key'] ?? null;

if (!$userid || !$image || !$type || !$key) {
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode(['error' => 'Invalid encryption data']);
    exit;
}

if ($security_key != SECURITY_KEY_PLAIN) {
    echo json_encode(['error' => 'Invalid key security']);
    exit;
}

$con = dbConnect();
$url = 'https://app.bpluspro.xyz/social/';

$field = ($type == 'Profile') ? 'image' : 'cover';

// Get old file
$oldSql = "SELECT $field FROM signup WHERE id = ?";
$stmt = $con->prepare($oldSql);
$stmt->bind_param("i", $userid);
$stmt->execute();
$stmt->bind_result($oldFile);
$stmt->fetch();
$stmt->close();

// Save new file
$decodedImage = base64_decode($image);
$fileName = time() . '_' . rand(1000, 9999) . '.jpg';
$filePath = 'images/' . $fileName;

if (!file_put_contents($filePath, $decodedImage)) {
    echo json_encode(['error' => 'File upload failed']);
    exit;
}

// UPDATE in signup
$updateSql = "UPDATE signup SET $field = ? WHERE id = ?";
$stmt = $con->prepare($updateSql);
$stmt->bind_param("si", $filePath, $userid);
$stmt->execute();
$stmt->close();

// DELETE old image
if (!empty($oldFile) && file_exists($oldFile)) {
    @unlink($oldFile);
}


echo json_encode([
    'status' => 'Successfully',
    'path' => $filePath
]);

mysqli_close($con);

?>
