<?php
// admin/users/edit_student.php
session_start();

// 1. Correct Pathing for subfolders
$projectRoot = dirname(dirname(__DIR__)); 
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

// --- UPDATED AUTH CHECK ---
// Now allows both admin and subadmin to edit student records
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php");
    exit();
}

$success = "";
$error = "";

// 2. Get Student ID from URL
$student_id = $_GET['id'] ?? '';

if (!$student_id) {
    header("Location: students.php");
    exit();
}

// 3. Handle Form Submission (Update Logic)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_student'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $fullname = $first_name . ' ' . $last_name;
    $reg_number = trim($_POST['reg_number']);
    $class_id = $_POST['class_id'];
    $gender = $_POST['gender'];
    $dob = $_POST['dob'];
    $parent_name = trim($_POST['parent_name']);
    $parent_phone = trim($_POST['parent_phone']);
    $address = trim($_POST['address']);
    $result_access = $_POST['result_access'];

    try {
        // Prepare the expanded update query
        $sql = "UPDATE students SET 
                first_name = ?, 
                last_name = ?, 
                fullname = ?, 
                reg_number = ?, 
                class_id = ?, 
                gender = ?, 
                dob = ?, 
                parent_name = ?, 
                parent_phone = ?, 
                address = ?, 
                result_access = ? 
                WHERE id = ?";
        
        $params = [
            $first_name, $last_name, $fullname, $reg_number, 
            $class_id, $gender, $dob, $parent_name, 
            $parent_phone, $address, $result_access, $student_id
        ];

        $update = $pdo->prepare($sql);
        $update->execute($params);
        $success = "Student records updated successfully!";
        
        // Refresh local $student variable to show updated info in form
        $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
        
    } catch (PDOException $e) {
        $error = "Error updating record: " . $e->getMessage();
    }
} else {
    // Initial Fetch of Current Student Data
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
}

if (!$student) {
    die("Student not found.");
}

// 5. Fetch Classes for the dropdown
$classes = $pdo->query("SELECT * FROM classes ORDER BY class_name ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Student | Admin Portal</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f0f2f5; padding: 20px; }
        .edit-card { background: white; padding: 30px; border-radius: 12px; max-width: 800px; margin: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { margin-bottom: 15px; }
        .full-width { grid-column: span 2; }
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #34495e; font-size: 13px; text-transform: uppercase; }
        input, select, textarea { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; }
        textarea { height: 80px; resize: none; }
        .btn-update { background: #27ae60; color: white; border: none; padding: 16px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; margin-top: 10px; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; font-weight: bold; }
        .profile-header { display: flex; align-items: center; gap: 20px; margin-bottom: 30px; background: #f8fafc; padding: 15px; border-radius: 10px; }
        .profile-img { width: 70px; height: 70px; border-radius: 50%; object-fit: cover; border: 3px solid #3498db; }
    </style>
</head>
<body>

<div class="edit-card">
    <a href="students.php" style="text-decoration:none; color:#3498db; font-weight:bold;">← Back to Student List</a>
    
    <div class="profile-header">
        <img src="../../uploads/students/<?= $student['photo'] ?>" class="profile-img" onerror="this.src='../../uploads/students/default.png'">
        <div>
            <h2 style="margin:0; color:#2c3e50;"><?= htmlspecialchars($student['fullname']) ?></h2>
            <small style="color:#7f8c8d;">Editing Student ID: <?= htmlspecialchars($student['reg_number']) ?></small>
        </div>
    </div>

    <?php if($success): ?>
        <div class="alert" style="background:#d4edda; color:#155724;"><?= $success ?></div>
    <?php endif; ?>

    <?php if($error): ?>
        <div class="alert" style="background:#f8d7da; color:#721c24;"><?= $error ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-grid">
            <div class="form-group">
                <label>First Name</label>
                <input type="text" name="first_name" value="<?= htmlspecialchars($student['first_name'] ?? '') ?>" required>
            </div>
            <div class="form-group">
                <label>Last Name</label>
                <input type="text" name="last_name" value="<?= htmlspecialchars($student['last_name'] ?? '') ?>" required>
            </div>

            <div class="form-group">
                <label>Registration Number</label>
                <input type="text" name="reg_number" value="<?= htmlspecialchars($student['reg_number'] ?? '') ?>" required>
            </div>
            <div class="form-group">
                <label>Class</label>
                <select name="class_id" required>
                    <?php foreach($classes as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= ($c['id'] == $student['class_id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['class_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Gender</label>
                <select name="gender" required>
                    <option value="Male" <?= ($student['gender'] == 'Male') ? 'selected' : '' ?>>Male</option>
                    <option value="Female" <?= ($student['gender'] == 'Female') ? 'selected' : '' ?>>Female</option>
                </select>
            </div>
            <div class="form-group">
                <label>Date of Birth</label>
                <input type="date" name="dob" value="<?= $student['dob'] ?>" required>
            </div>

            <div class="form-group">
                <label>Parent/Guardian Name</label>
                <input type="text" name="parent_name" value="<?= htmlspecialchars($student['parent_name'] ?? '') ?>" required>
            </div>
            <div class="form-group">
                <label>Parent Phone</label>
                <input type="text" name="parent_phone" value="<?= htmlspecialchars($student['parent_phone'] ?? '') ?>" required>
            </div>

            <div class="form-group full-width">
                <label>Residential Address</label>
                <textarea name="address" required><?= htmlspecialchars($student['address'] ?? '') ?></textarea>
            </div>

            <div class="form-group full-width">
                <label>Result Checking Access</label>
                <select name="result_access" style="<?= $student['result_access'] == 0 ? 'border-color: #e74c3c; background: #fff5f5;' : '' ?>">
                    <option value="1" <?= ($student['result_access'] == 1) ? 'selected' : '' ?>>Allowed (Active)</option>
                    <option value="0" <?= ($student['result_access'] == 0) ? 'selected' : '' ?>>Blocked (Fee Defaulter)</option>
                </select>
            </div>
        </div>

        <button type="submit" name="update_student" class="btn-update">Update Student Profile</button>
    </form>
</div>

</body>
</html>