<?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"]);
    $nic = trim($data["nic"]);
    $mobile = trim($data["mobile"]);
    $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 (!isValidNic($nic)) {
        $response["message"] = "Please enter valid NIC";
        echo json_encode($response); exit;
    } else if (!isValidMobile($mobile)) {
        $response["message"] = "Please enter valid mobile number";
        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 student ID
    if (!isset($_SESSION["user"]) || !isset($_SESSION["user"]["id"])) {
        $response["message"] = "You are not logged in.";
        echo json_encode($response); exit;
    }
    $student_id = $_SESSION["user"]["id"];

    // Check duplicates (email/nic)
    $rs = Database::search("SELECT * FROM `student` WHERE (`email` = '$email' OR `nic` = '$nic') AND `id` != '$student_id'");
    if ($rs->num_rows > 0) {
        $response["message"] = "Email or NIC 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 = "student_" . $student_id . "_" . time() . ".png";
        $imagePath = $folder . $fileName;
        $imageData = explode(",", $image)[1];
        file_put_contents($imagePath, base64_decode($imageData));

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

    // Update user info
    Database::iud("UPDATE `student` SET 
        `firstName`='$fname', 
        `lastName`='$lname', 
        `email`='$email', 
        `nic`='$nic', 
        `mobile`='$mobile', 
        `password`='$password'
        WHERE `id`='$student_id'
    ");

    // Update session with new data
    if (isset($_SESSION["user"])) {
        $_SESSION["user"]["firstName"] = $fname;
        $_SESSION["user"]["lastName"] = $lname;
        $_SESSION["user"]["email"] = $email;
        $_SESSION["user"]["nic"] = $nic;
        $_SESSION["user"]["mobile"] = $mobile;
        $_SESSION["user"]["password"] = $password;
        if ($newImagePath) {
            $_SESSION["user"]["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;
