<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../../imagekit/vendor/autoload.php";
include "../include/config.php";

use ImageKit\ImageKit;

/* ---------------------------
   Check login
---------------------------- */
if (!isset($_SESSION['studentid'])) {
    $_SESSION['error'] = "Please login first";
    header("Location: ../index.php");
    exit();
}

$studentid = $_SESSION['studentid'];

/* ---------------------------
   Check if image is uploaded
---------------------------- */
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== 0) {
    $_SESSION['error'] = "No image selected or upload error";
    header("Location: account.php");
    exit();
}

/* ---------------------------
   ImageKit Init
---------------------------- */
$imageKit = new ImageKit(
    "public_EypymL+l9sKGk/JHnWApsJ94ybA=",
    "private_T5LPQkxAMv70EVlUDk+RyUU3h5w=",
    "https://ik.imagekit.io/zamastudents"
);

/* ---------------------------
   Upload to ImageKit (ROOT "/")
---------------------------- */
try {
    $upload = $imageKit->upload([
        'file'             => fopen($_FILES['image']['tmp_name'], 'r'),
        'fileName'         => 'student_'.$studentid.'_'.time(),
        'folder'           => '/',          // ROOT folder
        'useUniqueFileName'=> true
    ]);

    if (isset($upload->error)) {
        throw new Exception($upload->error->message);
    }

    $image_url = $upload->result->url; // ✅ This is the ImageKit link

    /* ---------------------------
       Update database
    ---------------------------- */
    $sql = "UPDATE students SET image='$image_url' WHERE studentid='$studentid'";

    if (mysqli_query($conn, $sql)) {
        $_SESSION['image'] = $image_url; // update session for immediate use
        $_SESSION['success'] = "Profile image updated successfully!";
    } else {
        $_SESSION['error'] = "Database error: " . mysqli_error($conn);
    }

} catch (Exception $e) {
    $_SESSION['error'] = "Image upload failed: " . $e->getMessage();
}

header("Location: account.php");
exit();
?>
