<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../auth/auth.php';
require_once '../models/db_connection.php';
require_once '../models/user_model.php';

// Check if a student ID is provided in the URL
if (isset($_GET['id'])) {
    $studentId = intval($_GET['id']);
    $student_data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM students WHERE student_id = $studentId"));

    // Extract student data
    $fullname = $student_data['fullname'];
    $work = $student_data['work'];
    $education = $student_data['education'];
    $identNumber = $student_data['ident_number'];
    $gender = $student_data['gender'];
    $sensitiveCase = $student_data['sensitive_case'];
    $eyeProblems = $student_data['eye_problems'];
    $earProblems = $student_data['ear_problems'];
    $address = $student_data['address'];
    $street = $student_data['street'];
    $certnumber = $student_data['en_id'];
    $phoneNumber = $student_data['phone_number'];
    $image = $student_data['filename']; // Assuming you store the image file name
    $ages = $student_data['age'];

    // Get current courses for the student
    $studentCourses = [];
    $result = mysqli_query($conn, "SELECT sc.course_id FROM student_course sc WHERE sc.s_id = $studentId");
    while ($row = mysqli_fetch_assoc($result)) {
        $studentCourses[] = $row['course_id']; // store course IDs
    }

    // Get all courses for dropdown
    $allCourses = [];
    $courseQuery = mysqli_query($conn, "SELECT * FROM courses");
    while ($row = mysqli_fetch_assoc($courseQuery)) {
        $allCourses[] = $row;
    }
}

if (isset($_POST["editStudent"])) {
    // Retrieve form data
    $studentId = $_POST["id"];
    $fullname = $_POST['fullname'];
    $work = $_POST['work'];
    $education = $_POST['education'];
    $identNumber = $_POST['identNumber'];
    $gender = $_POST['gender'];
    $sensitiveCase = $_POST['sensitiveCase'];
    $eyeProblems = $_POST['eyeProblem'];
    $earProblems = $_POST['earProblem'];
    $address = $_POST['address'];
    $street = $_POST['street'];
    $phoneNumber = $_POST['phoneNumber'];
    $certnumber = $_POST['certnumber'];
    $age = $_POST['age'];
    $selectedCourse = $_POST['course_id'] ?? null;

    $user =  new User($conn);
    $userData = $user->getUserById($_SESSION['user']);
    $username = $userData[0]['username'];

    $file_name = $image; // default to existing image

    // Check if file was uploaded without errors
    if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
        $allowed_types = array("image/jpeg", "image/png", "image/gif");
        $file_type = $_FILES["image"]["type"];
        if (in_array($file_type, $allowed_types)) {
            $upload_dir = "../uploads/";
            $file_name = $_FILES["image"]["name"];
            move_uploaded_file($_FILES["image"]["tmp_name"], $upload_dir . $file_name);
        }
    }

    // Update students table
    $editstudent = mysqli_query($conn, "UPDATE students 
    SET 
        en_id = '$certnumber',
        fullname = '$fullname',
        ident_number = '$identNumber',
        street = '$street',
        address = '$address',
        work = '$work',
        education = '$education',
        gender = '$gender',
        phone_number = '$phoneNumber',
        eye_problems = '$eyeProblems',
        ear_problems = '$earProblems',
        sensitive_case = '$sensitiveCase',
        filename = '$file_name',
        reg_by = '$username',
        age = '$age'
    WHERE student_id = '$studentId'");

    // Update student_course table
    if ($selectedCourse) {
        $check = mysqli_query($conn, "SELECT * FROM student_course WHERE s_id = '$studentId'");
        if (mysqli_num_rows($check) > 0) {
            mysqli_query($conn, "UPDATE student_course 
                                 SET course_id = '$selectedCourse', en_date = NOW(), year = YEAR(NOW()) 
                                 WHERE s_id = '$studentId'");
        } else {
            mysqli_query($conn, "INSERT INTO student_course (s_id, course_id, en_date, year) 
                                 VALUES ('$studentId', '$selectedCourse', NOW(), YEAR(NOW()))");
        }
    }

    if ($editstudent) {
        echo "<script>
            alert('Student edited successfully');
            window.location.href = 'view_students.php';
        </script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Student | Edit Student</title>
    <?php include("../templates/header.php"); ?>
</head>

<body>
    <?php
    if (isset($_GET["message"])) {
        $message = $_GET["message"];
        echo "<script>alert('" . $message . "')</script>";
    }
    ?>
    <div class="container-scroller">
        <?php include("../templates/nav.php"); ?>
        <div class="container-fluid page-body-wrapper">
            <?php include("../templates/sidenav.php"); ?>
            <div class="main-panel">
                <div class="content-wrapper">
                    <div class="col-12 grid-margin">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Edit Student Form</h4>
                                <form class="form-sample" action="edit_student.php" method="POST" enctype="multipart/form-data">
                                    <p class="card-description">Personal info</p>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Fullname</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="fullname" value="<?php echo $fullname; ?>" required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Identification Number</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="identNumber" value="<?= $identNumber ?>" required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Certificate Number</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="certnumber" value="<?= $certnumber ?>" required>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Gender</label>
                                                <div class="col-sm-9">
                                                    <select class="form-control" name="gender">
                                                        <option <?= $gender == 'Male' ? 'selected' : '' ?>>Male</option>
                                                        <option <?= $gender == 'Female' ? 'selected' : '' ?>>Female</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Work</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="work" required value="<?= $work ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Eye Problem</label>
                                                <div class="col-sm-4">
                                                    <div class="form-check">
                                                        <label class="form-check-label">
                                                            <input type="radio" class="form-check-input" name="eyeProblem" value="No" <?= $eyeProblems=='No' ? 'checked':'' ?>>
                                                            No
                                                            <i class="input-helper"></i>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="col-sm-5">
                                                    <div class="form-check">
                                                        <label class="form-check-label">
                                                            <input type="radio" class="form-check-input" name="eyeProblem" value="Yes" <?= $eyeProblems=='Yes' ? 'checked':'' ?>>
                                                            Yes
                                                            <i class="input-helper"></i>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Ear Problem</label>
                                                <div class="col-sm-4">
                                                    <div class="form-check">
                                                        <label class="form-check-label">
                                                            <input type="radio" class="form-check-input" name="earProblem" value="No" <?= $earProblems=='No' ? 'checked':'' ?>>
                                                            No
                                                            <i class="input-helper"></i>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="col-sm-5">
                                                    <div class="form-check">
                                                        <label class="form-check-label">
                                                            <input type="radio" class="form-check-input" name="earProblem" value="Yes" <?= $earProblems=='Yes' ? 'checked':'' ?>>
                                                            Yes
                                                            <i class="input-helper"></i>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Sensitive case</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="sensitiveCase" required value="<?= $sensitiveCase ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <hr>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Address</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="address" required value="<?= $address ?>">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Street</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="street" required value="<?= $street ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Phone Number</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="phoneNumber" required value="<?= $phoneNumber ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Education</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="education" required value="<?= $education ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Course Selection -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Course</label>
                                                <div class="col-sm-9">
                                                    <select class="form-control" name="course_id">
                                                        <option value="">-- Select Course --</option>
                                                        <?php foreach ($allCourses as $course): ?>
                                                            <option value="<?= $course['course_id'] ?>" <?= in_array($course['course_id'], $studentCourses) ? 'selected':'' ?>>
                                                                <?= htmlspecialchars($course['name']) ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Passport</label>
                                                <div class="col-sm-9">
                                                    <input type="file" class="form-control" name="image" accept="image/*">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-sm-3 col-form-label">Age</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" name="age" value="<?= $ages ?>" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group row">
                                                <input type="hidden" name="id" value="<?= $_GET['id'] ?>">
                                                <div class="col-sm-9">
                                                    <button type="submit" name="editStudent" class="btn btn-dark btn-lg btn-block">Edit Student</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <?php include("../templates/footer.php"); ?>
            </div>
        </div>
    </div>
    <?php include("../templates/inc_scripts.php"); ?>
</body>

</html>
