<?php
session_start();

date_default_timezone_set('Asia/Manila');

include("auth_check.php");

// prevent double submission
if (isset($_SESSION['enroll_lock'])) {
    exit("Duplicate request blocked");
}
$_SESSION['enroll_lock'] = true;

$con = mysqli_connect("localhost","root","","WSAS");
if(!$con){ die("Connection failed: ".mysqli_connect_error()); }

mysqli_query($con, "SET time_zone = '+08:00'");

// Janna
require __DIR__ . '/../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendStudentEmail($email, $f_name, $l_name, $student_id_num, $password) {
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'wsas.cdlb@gmail.com';         
        $mail->Password = 'niyk jhkg ydnx iszt';      
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('wsas.cdlb@gmail.com', 'WSAS Administrator');
        $mail->addAddress($email, $f_name . ' ' . $l_name);

        $mail->isHTML(true);
        $mail->Subject = 'WSAS Account Created';

        $message = "Hello $f_name $l_name,<br><br>";
        $message .= "Your WSAS account has been created successfully. <br><br>";
        $message .= "<strong>Login Details: </strong><br>";
        $message .= "Student ID: $student_id_num <br>";
        $message .= "Password: $password <br><br>";
        $message .= "Login here: <a href='http://192.168.0.110/WSAS/login/student_login.php'> Student Login </a><br><br>";
        $message .= "IMPORTANT: Please change your password after your first login.<br><br>";
        $message .= "Best regards,<br>WSAS Administrator";

        $mail->Body = $message;
        $mail->AltBody = strip_tags(str_replace('<br>', "\n", $message));

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Message could not be sent.' . $mail->ErrorInfo);
        return false;
    }
}

if(isset($_POST['student_id'])){

    $student_id = $_POST['student_id'];
    $course_id = $_POST['course_id'];
    $sy_id = $_POST['sy_id'];
    $semester = $_POST['semester'];
    $year_level = $_POST['year_level'];
    $student_status = $_POST['student_status'];
    $date_enrolled = date("Y-m-d H:i:s");

    $sql = "INSERT INTO enroll_student
            (student_id, course_id, sy_id, semester, year_level, date_enrolled, student_status)
            VALUES ('$student_id','$course_id','$sy_id','$semester','$year_level','$date_enrolled','$student_status')";

    if(mysqli_query($con,$sql)){

        $enroll_id = mysqli_insert_id($con);

        $check_existing = mysqli_query($con, "
            SELECT soa_id 
            FROM soa 
            WHERE enroll_id = '$enroll_id'
            LIMIT 1
        ");

        if(mysqli_num_rows($check_existing) > 0){
            exit("SOA already created for this enrollment");
        }

        if(isset($_POST['subjects']) && count($_POST['subjects']) > 0){

            foreach($_POST['subjects'] as $subject_id){

                $prereq_q = mysqli_query($con, "
                    SELECT prerequisite_id 
                    FROM subject_prerequisite 
                    WHERE subject_id = '$subject_id'
                ");

                while($pr = mysqli_fetch_assoc($prereq_q)){

                    $prereq_id = $pr['prerequisite_id'];

                    $check_passed = mysqli_query($con, "
                        SELECT * FROM student_curriculum 
                        WHERE student_id = '$student_id'
                        AND subject_id = '$prereq_id'
                        AND sc_status = 'Completed'
                        AND sc_remark = 'Passed'
                    ");

                    if(mysqli_num_rows($check_passed) == 0){

                        $sub = mysqli_fetch_assoc(mysqli_query($con, "
                            SELECT subject_code FROM adminsubject WHERE subject_id='$subject_id'
                        "));

                        echo "<script>
                            alert('Cannot enroll {$sub['subject_code']} - prerequisite not completed.');
                            window.history.back();
                        </script>";
                        exit;
                    }
                }

                mysqli_query($con,"INSERT INTO student_subject
                (student_id, subject_id, subject_status, sy_id)
                VALUES ('$student_id','$subject_id','Enrolled','$sy_id')");

                mysqli_query($con,"UPDATE student_curriculum 
                    SET sc_status='Enrolled'
                    WHERE student_id='$student_id'
                    AND subject_id='$subject_id'");
            }
        }

        $comlab_subjects = [];

            foreach($_POST['subjects'] as $subject_id){

                $sub_q = mysqli_query($con,"SELECT subject_code FROM adminsubject WHERE subject_id='$subject_id'");
                $sub = mysqli_fetch_assoc($sub_q);

                $fee_q = mysqli_query($con,"
                    SELECT f.fee_name, f.subject_fee
                    FROM subject_fee sf
                    JOIN adminfee f ON sf.fee_id = f.fee_id
                    WHERE sf.subject_id='$subject_id'
                ");

                while($fee = mysqli_fetch_assoc($fee_q)){
                    if($fee['subject_fee'] == "Yes" && $fee['fee_name'] == "Computer Laboratory Fee"){
                        $comlab_subjects[$subject_id] = $sub['subject_code'];
                    }
                }
            }

            $full_lab_subject = null;

        if(count($comlab_subjects) > 0){

            // PRIORITY: CSPC
            foreach($comlab_subjects as $sid => $code){
                if(stripos($code, 'CSPC') !== false){
                    $full_lab_subject = $sid;
                    break;
                }
            }

            if(!$full_lab_subject){
                $highest = 0;

                foreach($comlab_subjects as $sid => $code){
                    if(preg_match('/CSCC(\d+)/i', $code, $match)){
                        $num = (int)$match[1];
                        if($num > $highest){
                            $highest = $num;
                            $full_lab_subject = $sid;
                        }
                    }
                }
            }

            // If still none → fallback (first subject)
            if(!$full_lab_subject){
                reset($comlab_subjects);
                $full_lab_subject = key($comlab_subjects);
            }
        }

        // --- DETERMINE IF STUDENT IS ALUMNI ---
        $alumni_check = mysqli_query($con, "SELECT * FROM alumni WHERE student_id='$student_id'");
        $is_alumni = mysqli_num_rows($alumni_check) > 0;

        // --- TUITION FEE ---


        $subject_total_units = 0; 
        $total_units_for_tuition = 0; 
        $subj_fee = 0;
        $special_fee = 0;

        $comlab_q = mysqli_query($con,"SELECT fee_amount FROM adminfee WHERE fee_name='Computer Laboratory Fee'");
        $comlab = mysqli_fetch_assoc($comlab_q);
        $comlab_fee = $comlab['fee_amount'];

        $other_comlab_q = mysqli_query($con,"SELECT fee_amount FROM adminfee WHERE fee_name='Other Comlab Fee'");
        $other_comlab = mysqli_fetch_assoc($other_comlab_q);
        $other_comlab_fee = $other_comlab['fee_amount'];

        $misc_q = mysqli_query($con,"SELECT fee_amount FROM adminfee WHERE fee_name='Miscellaneous Fee'");
        $misc = mysqli_fetch_assoc($misc_q);
        $misc_fee = $misc['fee_amount'];

       if(isset($_POST['subjects']) && count($_POST['subjects']) > 0){
            foreach($_POST['subjects'] as $subject_id){
                $sub_q = mysqli_query($con,"SELECT subject_code, total_unit FROM adminsubject WHERE subject_id='$subject_id'");
                $sub = mysqli_fetch_assoc($sub_q);

                $units = $sub['total_unit'];
                $subject_total_units += $units;

                $fee_q = mysqli_query($con,"
                    SELECT f.fee_name, f.fee_amount, f.subject_fee
                    FROM subject_fee sf
                    JOIN adminfee f ON sf.fee_id = f.fee_id
                    WHERE sf.subject_id='$subject_id'
                ");

                $is_special = false;

                while($fee = mysqli_fetch_assoc($fee_q)){

                    // COMPUTER LAB LOGIC
                    if($fee['subject_fee'] == "Yes" && stripos($fee['fee_name'], 'Computer Laboratory') !== false){

                        if($subject_id == $full_lab_subject){
                            $subj_fee += $comlab_fee; // FULL
                        } else {
                            $subj_fee += $other_comlab_fee; // OTHER
                        }

                    }

                    // OTHER SUBJECT FEES
                    elseif($fee['subject_fee'] == "Yes"){
                        $subj_fee += $fee['fee_amount'];
                    }

                    // SPECIAL FEES
                    elseif($fee['subject_fee'] == "Special"){
                        $special_fee += $fee['fee_amount'];
                        $is_special = true;
                    }
                }

                if(!$is_special){
                    $total_units_for_tuition += $units;
                }
                
            }
        }

        
        // --- TUITION FEE ---
        if($is_alumni){

            $alumni_q = mysqli_query($con, "
                SELECT alumni_tf 
                FROM alumni 
                WHERE student_id = '$student_id'
                LIMIT 1
            ");

            $alumni_data = mysqli_fetch_assoc($alumni_q);
            $tuition_fee = $alumni_data['alumni_tf'] ?? 0;

        } else {
            $tuition_q = mysqli_query($con,"SELECT fee_amount FROM adminfee WHERE fee_name='Tuition Fee'");
            $tuition_per_unit = mysqli_fetch_assoc($tuition_q)['fee_amount'];
            $tuition_fee = $tuition_per_unit * $total_units_for_tuition;
        }

        $discount_id = isset($_POST['discount_id']) && $_POST['discount_id'] !== '' 
            ? $_POST['discount_id'] 
            : null;
        $discount_percent = 0;
        $discounted_tuition_fee = $tuition_fee;

        if($discount_id){
            $disc_q = mysqli_query($con, "
                SELECT discount_amount, discount_name 
                FROM admindiscount 
                WHERE discount_id = '$discount_id'
            ");

            if($disc_q && mysqli_num_rows($disc_q) > 0){
                $disc = mysqli_fetch_assoc($disc_q);

                $discount_percent = floatval($disc['discount_amount']);

                $discounted_tuition_fee = $tuition_fee - ($tuition_fee * ($discount_percent / 100));
            }
        }
        
        $total_fee = $discounted_tuition_fee + $misc_fee + $special_fee + $subj_fee;

        // Ensure down payment is valid
        $down_payment = floatval($_POST['down_payment'] ?? 0);
        $down_payment = min($down_payment, $total_fee);

        $balance_fee = $total_fee - $down_payment;
        $monthly_fee = ($balance_fee > 0) ? $balance_fee / 4 : 0; // divide into 4 months
        $soa_date = date("Y-m-d");


        if($discount_id){
            mysqli_query($con, "
                INSERT INTO student_discount (student_id, discount_id)
                VALUES ('$student_id', '$discount_id')
            ");
        }
       $soa_insert = mysqli_query($con,"INSERT INTO soa
        (enroll_id, subject_total_units, tuition_fee, discount_id, discounted_tuition_fee, misc_fee, special_fee, subj_fee, total_fee, down_payment, balance_fee, monthly_fee, soa_date)
        VALUES 
        ('$enroll_id','$subject_total_units','$tuition_fee','$discount_id','$discounted_tuition_fee','$misc_fee','$special_fee','$subj_fee','$total_fee','$down_payment','$balance_fee','$monthly_fee','$soa_date')");
        
        if(!$soa_insert){
            die("SOA INSERT ERROR: " . mysqli_error($con));
        }

        $check_dp = mysqli_query($con, "
            SELECT sp_id 
            FROM student_payment
            WHERE student_id = '$student_id'
            AND sy_id = '$sy_id'
            AND payment_type = 'Downpayment'
            LIMIT 1
        ");

        if(mysqli_num_rows($check_dp) == 0){

            mysqli_query($con, "
                INSERT INTO student_payment
                (student_id, payment_type, spay_amount, sy_id, spay_method, created_at, spay_status)
                VALUES
                ('$student_id','Downpayment','$down_payment','$sy_id','N/A', NOW(),'Verified')
            ");
        }

        // JANNA
        // Get student info 
        $student_res = mysqli_query($con, "SELECT * FROM adminstudent WHERE student_id='$student_id'");
        $student = mysqli_fetch_assoc($student_res);

        // Hash the pass for storing in the db
        $hashed_password = password_hash($student['pword'], PASSWORD_DEFAULT);

        // Update the student record with hashed pass
        mysqli_query($con, "UPDATE adminstudent SET pword='$hashed_password' WHERE student_id='$student_id'");

        // Send the auto-generated pass via email
        $email_sent = sendStudentEmail(
            $student['email'],
            $student['f_name'],
            $student['l_name'],
            $student['student_id_num'],
            $student['pword']  
        );

        if(!$email_sent){
            error_log("Failed to send WSAS account email to ".$student['email']);
        }

        unset($_SESSION['enroll_lock']);
        header("Location: ../view/student_sub.php?student_id=$student_id&enrolled=1");
        exit;

    }else{
        echo "Error: ".mysqli_error($con);
    }

}
?>