<?php 
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

$id = $_GET['id'] ?? null;
if (!$id) { 
    echo "<script>window.location.href='manage_results.php';</script>"; 
    exit; 
}

// Fetch current result from database
$stmt = $pdo->prepare("SELECT * FROM results WHERE id = ?");
$stmt->execute([$id]);
$res = $stmt->fetch();

if (!$res) { 
    die("<div class='main-content p-5'><div class='alert alert-danger shadow-sm fw-bold text-center border-0'>Sorry! This result could not be found.</div></div>"); 
}

// Decode JSON details
$details = json_decode($res['details_json'], true);
$current_photo = (!empty($details['student_photo'])) ? '../' . $details['student_photo'] : '../assets/images/default_student.png';

$error = "";

// --- Update Logic ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $regi_no = trim($_POST['regi_no']);
    $year = trim($_POST['year']);
    
    // Handle Photo Update
    $photo_path = $details['student_photo'] ?? ""; 
    
    if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $filename = $_FILES['student_photo']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = 'std_' . $regi_no . '_' . time() . '.' . $ext;
            $upload_dir = '../uploads/students/';
            
            if (move_uploaded_file($_FILES['student_photo']['tmp_name'], $upload_dir . $new_filename)) {
                // Delete old photo if exists
                if (!empty($details['student_photo']) && file_exists('../' . $details['student_photo'])) {
                    unlink('../' . $details['student_photo']);
                }
                $photo_path = 'uploads/students/' . $new_filename;
            }
        } else {
            $error = "Only JPG, JPEG, PNG, or WEBP images are allowed.";
        }
    }

    if (empty($error)) {
        // Create new details array
        $new_details = [
            "Name" => $_POST['name'],
            "Roll" => $_POST['roll'],
            "Regi No" => $regi_no,
            "Date Of Birth" => $_POST['dob'],
            "Father's Name" => $_POST['father'],
            "Mothers Name" => $_POST['mother'],
            "Institute" => $_POST['institute'],
            "Duration Of the Course" => $_POST['duration'],
            "Branch Name" => $_POST['branch'],
            "Course Name" => $_POST['course_name'],
            "student_photo" => $photo_path
        ];

        $new_details_json = json_encode($new_details, JSON_UNESCAPED_UNICODE);

        try {
            $update = $pdo->prepare("UPDATE results SET regi_no = ?, passing_year = ?, class_name = ?, details_json = ?, gpa = ?, result_label = ? WHERE id = ?");
            $update->execute([$regi_no, $year, $_POST['course_name'], $new_details_json, $_POST['gpa'], $_POST['result'], $id]);
            echo "<script>window.location.href='manage_results.php?msg=updated';</script>";
            exit;
        } catch (PDOException $e) {
            $error = "Failed to update result: " . $e->getMessage();
        }
    }
}
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 35px; border-left: 6px solid var(--theme-green); }
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 40px; border-top: 6px solid var(--theme-green); }
    
    .section-divider { font-weight: 800; color: var(--theme-dark); border-left: 4px solid var(--theme-gold); padding-left: 15px; font-size: 16px; margin-bottom: 25px; background: #f8fafc; padding-top: 12px; padding-bottom: 12px; border-radius: 0 8px 8px 0; text-transform: uppercase; letter-spacing: 1px; }
    
    .form-label { font-weight: 700; color: var(--theme-dark); margin-bottom: 8px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-control, .form-select { border-radius: 10px; padding: 14px 20px; border: 1px solid #cbd5e1; background-color: var(--bg-soft); transition: 0.3s; font-size: 15px; font-weight: 500; color: var(--theme-dark); }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background-color: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    
    /* Image Upload Box */
    .photo-upload-box { width: 140px; height: 160px; border: 2px dashed #cbd5e1; border-radius: 15px; position: relative; overflow: hidden; background: #f1f5f9; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; transition: 0.3s; padding: 4px;}
    .photo-upload-box:hover { border-color: var(--theme-gold); background: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
    .photo-upload-box img { width: 100%; height: 100%; object-fit: cover; border-radius: 10px; }
    
    .btn-submit { background: var(--theme-green); color: #fff; padding: 16px 40px; border-radius: 12px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6,78,59,0.2); }
    .btn-submit:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-3px); box-shadow: 0 12px 25px rgba(6,78,59,0.3); }

    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* --- 📱 Mobile Responsive Fixes --- */
    @media (max-width: 768px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header > a.btn { width: 100%; justify-content: center; } 
        
        #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px;}
        .form-card { padding: 25px !important; }
    }
</style>

<div class="main-content p-4" style="background: var(--bg-soft); min-height: 100vh;">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3 shadow-sm" id="sidebarToggle">
                <i class="fas fa-bars text-dark"></i>
            </button>
            <h4 class="mb-0 fw-bold" style="color: var(--theme-green);">
                <i class="fas fa-edit me-2" style="color: var(--theme-gold);"></i> Edit Student Result
            </h4>
        </div>
        <a href="manage_results.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none mt-3 mt-md-0">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <?php if($error): ?> 
        <div class="alert alert-danger fade-up shadow-sm border-0 border-start border-danger border-4 mb-4 bg-white fw-bold">
            <i class="fas fa-exclamation-circle me-2 text-danger"></i> <?= htmlspecialchars($error); ?>
        </div> 
    <?php endif; ?>

    <div class="row justify-content-center fade-up" style="animation-delay: 0.1s;">
        <div class="col-xl-10 col-lg-11">
            <div class="form-card">
                <form method="POST" enctype="multipart/form-data">
                    
                    <div class="text-center mb-5 pb-4 border-bottom">
                        <div class="photo-upload-box shadow-sm">
                            <img id="preview" src="<?= htmlspecialchars($current_photo) ?>" onerror="this.src='https://via.placeholder.com/150'" alt="Student Photo">
                        </div>
                        <label class="btn btn-sm btn-light border rounded-pill px-4 py-2 fw-bold mb-2 cursor-pointer">
                            <i class="fas fa-camera me-2" style="color: var(--theme-green);"></i> Change Photo
                            <input type="file" name="student_photo" class="d-none" onchange="previewImage(event)" accept="image/*">
                        </label>
                        <p class="small text-muted mt-2"><i class="fas fa-info-circle"></i> Uploading a new photo will automatically replace the old one.</p>
                    </div>

                    <div class="section-divider" style="margin-top:0;">1. Basic Info (Identification)</div>
                    <div class="row g-4 mb-5">
                        <div class="col-md-4">
                            <label class="form-label">Registration No <span class="text-danger">*</span></label>
                            <input type="text" name="regi_no" class="form-control fw-bold text-success" value="<?= htmlspecialchars($res['regi_no']); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Passing Year <span class="text-danger">*</span></label>
                            <input type="text" name="year" class="form-control" value="<?= htmlspecialchars($res['passing_year']); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Roll Number <span class="text-danger">*</span></label>
                            <input type="text" name="roll" class="form-control" value="<?= htmlspecialchars($details['Roll'] ?? ''); ?>" required>
                        </div>
                    </div>

                    <div class="section-divider">2. Academic & Personal Details</div>
                    <div class="row g-4 mb-5">
                        <div class="col-md-6">
                            <label class="form-label">Student's Full Name <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($details['Name'] ?? ''); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Course Name</label>
                            <input type="text" name="course_name" class="form-control" value="<?= htmlspecialchars($res['class_name']); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Father's Name</label>
                            <input type="text" name="father" class="form-control" value="<?= htmlspecialchars($details['Father\'s Name'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Mother's Name</label>
                            <input type="text" name="mother" class="form-control" value="<?= htmlspecialchars($details['Mothers Name'] ?? ''); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Date of Birth</label>
                            <input type="text" name="dob" class="form-control" value="<?= htmlspecialchars($details['Date Of Birth'] ?? ''); ?>" placeholder="dd/mm/yyyy">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Result Status</label>
                            <select name="result" class="form-select fw-bold">
                                <option value="Passed" <?= ($res['result_label'] == 'Passed') ? 'selected' : ''; ?> class="text-success">Passed</option>
                                <option value="Failed" <?= ($res['result_label'] == 'Failed') ? 'selected' : ''; ?> class="text-danger">Failed</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Obtained GPA</label>
                            <input type="text" name="gpa" class="form-control fw-bold" style="color: var(--theme-green);" value="<?= htmlspecialchars($res['gpa']); ?>">
                        </div>
                    </div>

                    <div class="section-divider">3. Institute & Branch Info</div>
                    <div class="row g-4 mb-5">
                        <div class="col-md-6">
                            <label class="form-label">Institute Name</label>
                            <input type="text" name="institute" class="form-control" value="<?= htmlspecialchars($details['Institute'] ?? 'Ahmad Online Academy'); ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Course Duration</label>
                            <input type="text" name="duration" class="form-control" value="<?= htmlspecialchars($details['Duration Of the Course'] ?? ''); ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Branch</label>
                            <input type="text" name="branch" class="form-control" value="<?= htmlspecialchars($details['Branch Name'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="text-center mt-4 border-top pt-5">
                        <button type="submit" class="btn btn-submit shadow w-100 d-md-inline-block" style="max-width: 300px;">
                            <i class="fas fa-save me-2"></i> Update Result
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Image Preview Script
    function previewImage(event) {
        var reader = new FileReader();
        reader.onload = function() {
            var output = document.getElementById('preview');
            output.src = reader.result;
        }
        reader.readAsDataURL(event.target.files[0]);
    }

    // Mobile Sidebar Toggle
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>