<?php
session_start();
require_once 'db.php';

// Auth check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}
// Validate request
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['regNo'])) {
    $_SESSION['error'] = "Invalid request.";
    header("Location: students.php");
    exit;
}
$regNo = $_POST['regNo'];
// Fetch old data (for keeping/deleting old files)
$stmt = $conn->prepare("SELECT photo_path, aadhar_card_path FROM students WHERE unique_reg_number = ?");
$stmt->bind_param("s", $regNo);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    $_SESSION['error'] = "Student not found.";
    header("Location: students.php");
    exit;
}
$oldData = $result->fetch_assoc();
$stmt->close();
// Get form data
$fullName              = trim($_POST['fullName'] ?? '');
$school                = trim($_POST['school'] ?? '');
$classGrade            = trim($_POST['classGrade'] ?? '');
$section               = trim($_POST['section'] ?? '');
$admissionNumber       = trim($_POST['admissionNumber'] ?? '');
$dob                   = trim($_POST['dob'] ?? '');
$gender                = trim($_POST['gender'] ?? '');
$fatherName            = trim($_POST['fatherName'] ?? '');
$fatherMobile          = trim($_POST['fatherMobile'] ?? '');
$motherName            = trim($_POST['motherName'] ?? '');
$motherMobile          = trim($_POST['motherMobile'] ?? '');
$permanentAddress      = trim($_POST['permanentAddress'] ?? '');
$correspondenceAddress = trim($_POST['correspondenceAddress'] ?? '');
$preferredLanguage     = trim($_POST['preferredLanguage'] ?? '');
$hobbies               = trim($_POST['hobbies'] ?? '');
$achievementType       = trim($_POST['achievementType'] ?? '');
$siblings              = trim($_POST['siblings'] ?? 'No');
$siblingDetails        = trim($_POST['siblingDetails'] ?? '');
$stationary            = trim($_POST['stationary'] ?? '');
$state                 = trim($_POST['state'] ?? '');
$district              = trim($_POST['district'] ?? '');
$pincode               = trim($_POST['pincode'] ?? '');

// File paths
$photoDbPath  = $oldData['photo_path'];
$aadharDBPath = $oldData['aadhar_card_path'];

// Upload directory
$uploadDir = __DIR__ . "/uploads/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Allowed file extensions
$allowedImageExt = ['jpg', 'jpeg', 'png', 'gif'];
$allowedDocExt   = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];

// --- Student Photo Upload ---
if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
    if ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
        $_SESSION['error'] = "Photo must be less than 2MB.";
        header("Location: edit_student.php?reg=" . urlencode($regNo));
        exit;
    }
    $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedImageExt)) {
        $_SESSION['error'] = "Invalid photo format. Only JPG, PNG, GIF allowed.";
        header("Location: edit_student.php?reg=" . urlencode($regNo));
        exit;
    }
    $photoPathname = "photo_" . time() . "_" . uniqid() . "." . $ext;
    $targetPath = $uploadDir . $photoPathname;
    if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetPath)) {
        if (!empty($oldData['photo_path']) && file_exists(__DIR__ . "/" . $oldData['photo_path'])) {
            unlink(__DIR__ . "/" . $oldData['photo_path']);
        }
        $photoDbPath = "uploads/" . $photoPathname;
    }
}

// --- Aadhaar Card Upload ---
if (isset($_FILES['aadharCard']) && $_FILES['aadharCard']['error'] === UPLOAD_ERR_OK) {
    if ($_FILES['aadharCard']['size'] > 2 * 1024 * 1024) {
        $_SESSION['error'] = "Aadhaar card must be less than 2MB.";
        header("Location: edit_student.php?reg=" . urlencode($regNo));
        exit;
    }
    $ext = strtolower(pathinfo($_FILES['aadharCard']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedDocExt)) {
        $_SESSION['error'] = "Invalid Aadhaar format. Only JPG, PNG, GIF, PDF allowed.";
        header("Location: edit_student.php?reg=" . urlencode($regNo));
        exit;
    }
    $aadharPathname = "aadhar_" . time() . "_" . uniqid() . "." . $ext;
    $targetPath = $uploadDir . $aadharPathname;
    if (move_uploaded_file($_FILES['aadharCard']['tmp_name'], $targetPath)) {
        if (!empty($oldData['aadhar_card_path']) && file_exists(__DIR__ . "/" . $oldData['aadhar_card_path'])) {
            unlink(__DIR__ . "/" . $oldData['aadhar_card_path']);
        }
        $aadharDBPath = "uploads/" . $aadharPathname;
    }
}

// --- Update Student Record ---
$stmt = $conn->prepare("
    UPDATE students SET 
        full_name = ?, 
        school = ?, 
        class_grade = ?, 
        section = ?, 
        admission_number = ?, 
        dob = ?, 
        gender = ?, 
        father_name = ?, 
        father_guardian_mobile = ?, 
        mother_name = ?, 
        mother_mobile = ?, 
        permanent_address = ?, 
        correspondence_address = ?, 
        preferred_language = ?, 
        hobbies = ?, 
        achievement_type = ?, 
        siblings = ?, 
        sibling_details = ?, 
        photo_path = ?, 
        aadhar_card_path = ?,
        stationary = ?,
        state = ?,
        district = ?,
        pincode = ?
    WHERE unique_reg_number = ?
");

$stmt->bind_param(
    "sssssssssssssssssssssssss",
    $fullName,
    $school,
    $classGrade,
    $section,
    $admissionNumber,
    $dob,
    $gender,
    $fatherName,
    $fatherMobile,
    $motherName,
    $motherMobile,
    $permanentAddress,
    $correspondenceAddress,
    $preferredLanguage,
    $hobbies,
    $achievementType,
    $siblings,
    $siblingDetails,
    $photoDbPath,
    $aadharDBPath,
    $stationary,   //  correct place
    $state,   //  correct place
    $district,   // correct place
    $pincode,   //  correct place
    $regNo         //  WHERE condition
);

if ($stmt->execute()) {
    $_SESSION['success'] = "Student updated successfully.";
    header("Location: view_student_profile.php?reg=" . urlencode($regNo));
    exit;
} else {
    $_SESSION['error'] = "Error updating student: " . $stmt->error;
    header("Location: edit_student.php?reg=" . urlencode($regNo));
    exit;
}

$stmt->close();
$conn->close();
?>
