<?php
// 1. REVEAL CRITICAL ERRORS SEAMLESSLY IF SOMETHING CRASHES
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once 'db.php';

$message = "";
$student = null;
$search_matric = isset($_POST['search_matric']) ? trim($_POST['search_matric']) : (isset($_GET['ref_matric']) ? trim($_GET['ref_matric']) : '');

// 2. ACTION: LOOKUP STUDENT PROFILE BY MATRIC NUMBER
if (!empty($search_matric)) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM students WHERE UPPER(matric_number) = UPPER(?)");
        $stmt->execute([$search_matric]);
        $student = $stmt->fetch();
        
        if (!$student && isset($_POST['search_btn'])) {
            $message = "<div class='alert alert-warning'>⚠️ No active student account profile found for Matric Number: '" . htmlspecialchars($search_matric) . "'</div>";
        }
    } catch (\PDOException $e) {
        $message = "<div class='alert alert-danger'>❌ Search Fault: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}

// 3. ACTION: UPDATE MODIFIED DETAILS MATRIX
if (isset($_POST['update_student_profile'])) {
    $student_id = intval($_POST['student_id']);
    $new_matric = trim($_POST['m_num']);
    $new_name   = trim($_POST['f_name']);
    $new_sex    = $_POST['sex_val'];
    $new_dept   = trim($_POST['dept_val']);
    $new_lvl    = trim($_POST['lvl_val']);
    $new_prog   = trim($_POST['program_val']);
    $new_sess   = trim($_POST['session_val']);
    $new_pass   = trim($_POST['pass_val']);

    try {
        // Base update statement without modifying the photograph slot initially
        $sql = "UPDATE students SET matric_number = ?, full_name = ?, sex = ?, department = ?, student_level = ?, program = ?, session = ?, password = ? WHERE id = ?";
        $params = [$new_matric, $new_name, $new_sex, $new_dept, $new_lvl, $new_prog, $new_sess, $new_pass, $student_id];

        // Process a new photo upload if the admin chose a new file
        if (isset($_FILES['photo_upload']) && $_FILES['photo_upload']['error'] == 0) {
            $imgData = file_get_contents($_FILES['photo_upload']['tmp_name']);
            $sql = "UPDATE students SET matric_number = ?, full_name = ?, sex = ?, department = ?, student_level = ?, program = ?, session = ?, password = ?, photography = ? WHERE id = ?";
            $params = [$new_matric, $new_name, $new_sex, $new_dept, $new_lvl, $new_prog, $new_sess, $new_pass, $imgData, $student_id];
        }

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        $message = "<div class='alert alert-success'>✅ Success: Student profile details for <strong>" . htmlspecialchars($new_matric) . "</strong> updated successfully!</div>";
        
        // Refresh the search matrix cache to reveal edited fields instantly
        $search_matric = $new_matric;
        $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
    } catch (\PDOException $e) {
        $message = "<div class='alert alert-danger'>❌ Update Failure: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Student Information</title>
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .card { background: #fdfdfd; padding: 22px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 20px; border-top: 4px solid #007bff; }
        .card-orange { border-top-color: #ffc107; }
        input, select { width: 100%; padding: 11px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
        .btn { padding: 11px 20px; background: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; }
        .btn-search { background: #17a2b8; display: inline-block; width: auto; margin-top: 5px; }
        .btn-save { background: #ffc107; color: #222; width: 100%; margin-top: 12px; }
        .btn-save:hover { background: #e0a800; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 18px; font-weight: bold; font-size: 14px; text-align: left; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        .profile-img-preview { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 3px solid #dee2e6; display: block; margin-bottom: 10px; background: #eee; }
    </style>
</head>
<body>

    <h2 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 8px; font-size: 20px;">Edit Student Information Panel</h2>
    
    <!-- Render alert notifications box -->
    <?php echo $message; ?>

    <!-- STEP 1: SEARCH FILTER TARGET COMPONENT -->
    <div class="card">
        <h4 style="margin-top:0; color:#007bff; font-size: 15px;">Search Student Account to Edit</h4>
        <form method="POST" action="edit_student.php">
            <label style="font-size: 12px; font-weight: bold; color: #555;">Enter Student Matric Number:</label>
            <input type="text" name="search_matric" value="<?php echo htmlspecialchars($search_matric); ?>" placeholder="e.g., CSC/2026/001" required autocomplete="off">
            <button type="submit" name="search_btn" class="btn btn-search">Lookup Profile Record</button>
        </form>
    </div>

    <!-- STEP 2: PROFILE EDITOR CARD FORM -->
    <?php if (!empty($student)) { ?>
        <div class="card card-orange">
            <h4 style="margin-top:0; color:#e0a800; font-size: 15px;">Modify Details Parameters for: <u><?php echo htmlspecialchars($student['full_name']); ?></u></h4>
            
            <form method="POST" enctype="multipart/form-data" action="edit_student.php">
                <input type="hidden" name="student_id" value="<?php echo $student['id']; ?>">
                
                <div style="display: flex; gap: 20px; align-items: center; margin-bottom: 15px; background: #f8f9fa; padding: 15px; border-radius: 6px;">
                    <?php if (!empty($student['photography'])) { ?>
                        <img class="profile-img-preview" src="data:image/jpeg;base64,<?php echo base64_encode($student['photography']); ?>" alt="Profile">
                    <?php } else { ?>
                        <div class="profile-img-preview" style="display:flex; align-items:center; justify-content:center; font-size:36px; color:#aaa;">👤</div>
                    <?php } ?>
                    <div>
                        <label style="font-size: 12px; font-weight: bold; color: #555; display:block;">Change / Update Profile Picture (Leave blank to keep current image):</label>
                        <input type="file" name="photo_upload" accept="image/*" style="border:none; padding:0; margin:5px 0;">
                    </div>
                </div>

                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px;">
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Matric Number:</label>
                        <input type="text" name="m_num" value="<?php echo htmlspecialchars($student['matric_number']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Full Name:</label>
                        <input type="text" name="f_name" value="<?php echo htmlspecialchars($student['full_name']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Gender/Sex:</label>
                        <select name="sex_val" required>
                            <option value="Male" <?php echo ($student['sex'] === 'Male') ? 'selected' : ''; ?>>Male</option>
                            <option value="Female" <?php echo ($student['sex'] === 'Female') ? 'selected' : ''; ?>>Female</option>
                        </select>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Department:</label>
                        <input type="text" name="dept_val" value="<?php echo htmlspecialchars($student['department']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Student Level:</label>
                        <input type="text" name="lvl_val" value="<?php echo htmlspecialchars($student['student_level']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Program:</label>
                        <input type="text" name="program_val" value="<?php echo htmlspecialchars($student['program']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Academic Session:</label>
                        <input type="text" name="session_val" value="<?php echo htmlspecialchars($student['session']); ?>" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; font-weight: bold; color: #666;">Portal Password (Plain Text):</label>
                        <input type="text" name="pass_val" value="<?php echo htmlspecialchars($student['password']); ?>" required>
                    </div>
                </div>

                <button type="submit" name="update_student_profile" class="btn btn-save">💾 Save Profile Parameter Modifications</button>
            </form>
        </div>
    <?php } ?>

</body>
</html>
