<?php
// Suppress any output before JSON
ob_start();

session_start();
include "connection.php";
include "validation.php";

// Clear any output buffer
ob_clean();

header("Content-Type: application/json");

$response = [
    "status" => false,
    "message" => ""
];

try {
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    $fname = trim($data["fname"]);
    $lname = trim($data["lname"]);
    $email = trim($data["email"]);
    $password = trim($data["password"]);
    $image = isset($data["image"]) ? $data["image"] : null;

    // --- Validations ---
    if (empty($fname)) {
        $response["message"] = "Please enter first name";
        echo json_encode($response); exit;
    } else if (strlen($fname) > 45) {
        $response["message"] = "First name must be less than 45 characters";
        echo json_encode($response); exit;
    } else if (empty($lname)) {
        $response["message"] = "Please enter last name";
        echo json_encode($response); exit;
    } else if (!isValidEmail($email)) {
        $response["message"] = "Please enter valid email";
        echo json_encode($response); exit;
    } else if (!isValidPassword($password)) {
        $response["message"] = "Invalid password format (min 8 chars, 1 upper, 1 lower, 1 number, 1 special)";
        echo json_encode($response); exit;
    }

    // Assume logged-in admin ID
    if (!isset($_SESSION["admin"]) || !isset($_SESSION["admin"]["id"])) {
        $response["message"] = "You are not logged in.";
        echo json_encode($response); exit;
    }
    $admin_id = $_SESSION["admin"]["id"];

    // Check duplicates (email)
    $rs = Database::search("SELECT * FROM `admin` WHERE `email` = '$email' AND `id` != '$admin_id'");
    if ($rs->num_rows > 0) {
        $response["message"] = "Email already in use.";
        echo json_encode($response); exit;
    }

    // Image upload (Base64 → File)
    $newImagePath = null;
    if ($image) {
        $folder = "../../Uploads/Profile/";
        if (!file_exists($folder)) {
            mkdir($folder, 0777, true);
        }

        $fileName = "admin_" . $admin_id . "_" . time() . ".png";
        $imagePath = $folder . $fileName;
        $imageData = explode(",", $image)[1];
        file_put_contents($imagePath, base64_decode($imageData));

        $newImagePath = "Uploads/Profile/" . $fileName;
        Database::iud("UPDATE `admin` SET `profile_img`='" . $newImagePath . "' WHERE `id`='$admin_id'");
    }

    // Update admin info
    Database::iud("UPDATE `admin` SET 
        `fname`='$fname', 
        `lname`='$lname', 
        `email`='$email', 
        `password`='$password'
        WHERE `id`='$admin_id'
    ");

    // Update session with new data
    if (isset($_SESSION["admin"])) {
        $_SESSION["admin"]["fname"] = $fname;
        $_SESSION["admin"]["lname"] = $lname;
        $_SESSION["admin"]["email"] = $email;
        $_SESSION["admin"]["password"] = $password;
        if ($newImagePath) {
            $_SESSION["admin"]["profile_img"] = $newImagePath;
        }
    }

    $response["status"] = true;
    $response["message"] = "Profile updated successfully!";
    if ($newImagePath) {
        $response["newImage"] = $newImagePath;
    }

} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;

