<?php include("../database/auth_check.php"); ?>

<?php
$con = mysqli_connect("localhost","root","","WSAS");
if (!$con) {
    die("Database connection failed");
}

if (!isset($_GET['student_id'])) {
    header("Location: ../adminpanel/adminstudents.php");
    exit;
}

$student_id = (int) $_GET['student_id'];

$current_q = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");

if (!$current_q || mysqli_num_rows($current_q) == 0) {
    die("No active school year found");
}

$current = mysqli_fetch_assoc($current_q);
$current_sy_id = (int)$current['sy_id'];
$is_currently_enrolled = false;

$enroll_id = 0;
$last_sem = '';
$last_sy_id = 0;

$check_current = mysqli_query($con, "
    SELECT enroll_id, date_enrolled
    FROM enroll_student 
    WHERE student_id = $student_id 
      AND sy_id = $current_sy_id
    LIMIT 1
");

if ($check_current && mysqli_num_rows($check_current) > 0) {
    $enroll = mysqli_fetch_assoc($check_current);
    $is_currently_enrolled = true;
} else {
    $enroll = null;
}
$current_sem   = trim($current['semester']);


$enroll_q = mysqli_query($con, "
    SELECT * 
    FROM enroll_student 
    WHERE student_id = $student_id
    ORDER BY enroll_id DESC
    LIMIT 1
");

if ($enroll_q && mysqli_num_rows($enroll_q) > 0) {
    $enroll = mysqli_fetch_assoc($enroll_q);

    $enroll_id  = $enroll['enroll_id'];
    $last_sem   = $enroll['semester'];
    $last_sy_id = $enroll['sy_id'];
} else {
    $enroll = [
        'enroll_id' => 0,
        'date_enrolled' => date('Y-m-d H:i:s')
    ];
}

$student_sql = "
SELECT adminstudent.*, admincourse.course_name
FROM adminstudent
LEFT JOIN admincourse 
ON adminstudent.course_id = admincourse.course_id
WHERE adminstudent.student_id = $student_id
";

$student_res = mysqli_query($con, $student_sql);
if (!$student_res) {
    die("Student Query Error: " . mysqli_error($con));
}

$student = mysqli_fetch_assoc($student_res);

// Fetch fees if they exist
$fee_sql = "
    SELECT 
        s.tuition_fee, 
        s.misc_fee, 
        s.special_fee, 
        s.subj_fee, 
        s.total_fee, 
        s.down_payment, 
        s.balance_fee, 
        s.monthly_fee,
        s.discounted_tuition_fee 
    FROM soa s
    WHERE s.enroll_id = '$enroll_id'
    LIMIT 1
";
$fee_res = mysqli_query($con, $fee_sql);
if(!$fee_res){
    die("SOA Query Error: " . mysqli_error($con));
}
$fee = mysqli_fetch_assoc($fee_res);

// Initialize fees if not found
if (!$fee) {
    $fee = [
        'tuition_fee' => 0,
        'misc_fee' => 0,
        'special_fee' => 0,
        'subj_fee' => 0,
        'total_fee' => 0,
        'down_payment' => 0,
        'balance_fee' => 0,
        'monthly_fee' => 0,
        'discounted_tuition_fee' => 0
    ];
} else {
    // Ensure discounted tuition exists
    if(!isset($fee['discounted_tuition_fee'])){
        $fee['discounted_tuition_fee'] = $fee['tuition_fee'];
    }
}

// Fetch only enrolled subjects for this student
$subjects = [];
$total_units = 0;

$subject_sql = "
SELECT 
    a.subject_id,
    a.subject_code AS code,
    a.subject_name AS name,
    (a.lecture_unit + a.lab_unit) AS units,
    f.fee_name,
    f.fee_amount,
    f.subject_fee
FROM student_curriculum sc
JOIN adminsubject a ON sc.subject_id = a.subject_id
JOIN adminstudent st ON sc.student_id = st.student_id
JOIN course_subject cs 
    ON sc.subject_id = cs.subject_id 
    AND cs.course_id = st.course_id
LEFT JOIN subject_fee sf ON a.subject_id = sf.subject_id
LEFT JOIN adminfee f ON sf.fee_id = f.fee_id
WHERE sc.student_id = $student_id
  AND sc.sc_status = 'enrolled'
ORDER BY cs.year_level ASC, FIELD(cs.semester,'1st','2nd','Summer')
";

$subject_res = mysqli_query($con, $subject_sql);


if($subject_res){
    while($row = mysqli_fetch_assoc($subject_res)){
        $id = $row['subject_id'];

        if(!isset($subjects[$id])){
            $subjects[$id] = [
                'code' => $row['code'],
                'name' => $row['name'],
                'units' => $row['units'],
                'fees' => []
            ];
            $total_units += $row['units'];
        }

        if(!empty($row['fee_name'])){
            $subjects[$id]['fees'][] = [
                'name' => $row['fee_name'],
                'amount' => $row['fee_amount'],
                'type' => $row['subject_fee']
            ];
        }
    }
} else {
    die("Subjects Query Error: " . mysqli_error($con));
}

$discount_percent = 0;
$discount_name = '';

$discount_q = mysqli_query($con, "
    SELECT d.discount_name, d.discount_amount
    FROM student_discount sd
    JOIN admindiscount d ON sd.discount_id = d.discount_id
    JOIN enroll_student e ON sd.student_id = e.student_id
    WHERE sd.student_id = $student_id
    LIMIT 1
");

if($discount_q && mysqli_num_rows($discount_q) > 0){
    $disc = mysqli_fetch_assoc($discount_q);
    $discount_percent = floatval($disc['discount_amount']);
    $discount_name = $disc['discount_name'];
}

// Check if student is already enrolled
$is_currently_enrolled = false;
$enroll = null;

$check_current = mysqli_query($con, "
    SELECT * 
    FROM enroll_student 
    WHERE student_id = $student_id 
      AND sy_id = $current_sy_id
    LIMIT 1
");

if ($check_current && mysqli_num_rows($check_current) > 0) {
    $enroll = mysqli_fetch_assoc($check_current);
    $is_currently_enrolled = true;
}
if (!$is_currently_enrolled) {

    // FORCE EVERYTHING EMPTY
    $subjects = [];
    $fee = [
        'tuition_fee' => 0,
        'misc_fee' => 0,
        'special_fee' => 0,
        'subj_fee' => 0,
        'total_fee' => 0,
        'down_payment' => 0,
        'balance_fee' => 0,
        'monthly_fee' => 0,
        'discounted_tuition_fee' => 0
    ];

    $payments = [];
    $monthly_payments = [];
    $remaining_balance = 0;
}
$balance = floatval($fee['balance_fee'] ?? 0);





// Payments
$payments = [];

$stmt = $con->prepare("
    SELECT spay_amount AS amount,
       description,
       verified_at,
       spay_method AS payment_method
FROM student_payment
WHERE student_id = ?
AND spay_status = 'Verified'
ORDER BY verified_at ASC
");



if (!$stmt) {
    die("Prepare failed: " . $con->error);
}
$stmt->bind_param("i", $student_id);

$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $payments[] = $row;
}
$stmt->close();

// Monthly payments
$monthly_payments = [];
$enroll_date = $enroll['date_enrolled'] ?? date('Y-m-d H:i:s');
/* Downpayment */
$monthly_payments[] = [
    'month' => 'Downpayment',
    'due' => '-',
    'amount_due' => $fee['down_payment'],
    'amount_paid' => $fee['down_payment'],
    'mode' => 'Cash',
    'date_paid' => $enroll_date,
    'status' => 'Paid'
];

$remainingPayments = $payments;


$enroll_id = $enroll['enroll_id'] ?? 0;

$startDate = new DateTime($enroll_date, new DateTimeZone('Asia/Manila'));
$today = new DateTime("now", new DateTimeZone('Asia/Manila'));

for ($i = 1; $i <= 4; $i++) {

    $dueDate = clone $startDate;
    $dueDate->modify("+$i month");
    $dueDate->modify("last day of this month");

    $pay = array_shift($remainingPayments) ?? [];

    $paidAmount = $pay['amount'] ?? 0;
    $paidDate   = $pay['verified_at'] ?? '-';
    $mode       = $pay['payment_method'] ?? '-';

    if ($paidAmount > 0) {
        $status = 'Paid';
    } else {
        $status = ($today < $dueDate) ? '-' : 'Unpaid';
    }

    $monthly_payments[] = [
        'month' => $i,
        'due' => $dueDate->format('F d, Y'),
        'amount_due' => $fee['monthly_fee'],
        'amount_paid' => $paidAmount,
        'mode' => $mode,
        'date_paid' => $paidDate,
        'status' => $status
    ];
}
$balance = isset($fee['balance_fee']) ? floatval($fee['balance_fee']) : 0;
$total_paid = 0;

foreach ($payments as $p) {
    $total_paid += floatval($p['amount']);
}

// Remaining balance = original balance - payments
$remaining_balance = floatval($fee['balance_fee']) - $total_paid;

// Prevent negative balance
if ($remaining_balance < 0) {
    $remaining_balance = 0;
}

$current_sem_clean = strtolower(trim($current_sem));
$last_sem_clean    = strtolower(trim($last_sem));


$no_balance = ($remaining_balance <= 0);

$is_enrolled = $enroll ? true : false;

?>


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

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Students' Information - Admin</title>
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="../Style/navstyle.css">

<style>

.dashboard-container {
  display: flex;
  height: 100vh;
}

.mainbar {
    margin-left: 260px;
    width: calc(100% - 260px);
    flex: 1;
    display: flex;
    flex-direction: column;
}

.mainbar-context {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.container {
  display: flex;
  gap: 20px;
  width: 100%;
}

.main-layout {
    width: 100%;
}


.subject {
  background-color: #4a9c3f;
  color: white;
  padding: 20px;
  flex: 1;
  min-width: 200px;
  border-radius: 10px;
  text-align: center;
}

.container1 {
  display: flex;
  padding: 10px;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

h2 {
  font-size: 18px;
  margin-bottom: 10px;
}

h3 {
  font-size: 16px;
  margin-bottom: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}


table th, table td {
  padding: 8px 10px; 
  font-size: 13px;  
  text-align: center;
}

table th {
  background-color: #4a9c3f;
  color: #fff;
  font-weight: 600;
}

table td {
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

table tr:nth-child(even) td {
  background-color: #f9f9f9;
}

table tr:hover td {
  background-color: rgba(74, 156, 63, 0.1);
  transition: background-color 0.3s ease;
}

.student-soa-table h2 {
  margin-bottom: 15px;
  color: #2b5820;
}

table tr:hover {
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}


@media (max-width: 1024px) {
  .mainbar {
    margin-left: 0; 
    margin-top: 70px;
  }

  .dashboard-container {
    flex-direction: column;
  }
}

.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background: white;
  width: 400px;
  margin: 10% auto;
  padding: 20px;
  border-radius: 10px;
  animation: pop 0.3s ease;
}

.close-btn {
  float: right;
  cursor: pointer;
  font-size: 25px;
  padding: 5px;
}

.open-btn {
  background: #4a9c3f;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 13px;
}

@keyframes pop {
  from { transform: scale(0.7); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.main-layout {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.bottom-layout {
    display: flex;
    gap: 12px;
    width: 100%;
    align-items: stretch;
}


.subjects-section {
    width: 60%;
    flex: 1.5; 
}

.computation-section {
    width: 40%;
    flex: 1;
}

.student-info-section,
.subjects-section,
.computation-section,
.monthly-payment-section {
    background: #fff;
    padding: 12px;
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.08);
    width: 100%;
}

.payment-table th,
.payment-table td {
    padding: 8px 10px; 
    font-size: 13px; 
    text-align: center;
}

.payment-table th {
    background-color: #4a9c3f;
    color: #fff;
    font-weight: 600;
}
</style>

<body> 
   <div class="dashboard-container">
    <!-- Left Sidebar -->
    <?php include('../adminpanel/adminnav.php'); ?>

    <!-- Mainbar / Main Content -->
    <aside class="mainbar">

      <div class="mainbar-context">
        <div class="container">
            <div class="main-layout">

    <!-- TOP: STUDENT INFO -->
    

    <!-- BOTTOM: 2 COLUMNS -->
    <div class="bottom-layout">

        <!-- LEFT: SUBJECTS -->
        <div class="subjects-section">
        <h2>Student Information</h2>

        <table class="student-info-table">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Name</th>
                    <th>Sex</th>
                    <th>Course</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><?= $student['student_id_num']; ?></td>
                    <td><?= $student['f_name'] . ' ' . $student['l_name']; ?></td>
                    <td><?= $student['sex']; ?></td>
                    <td><?= $student['course_name']; ?></td>
                    <td><?= $student['email']; ?></td>
                </tr>
            </tbody>
        </table><br>
            <h3>Subjects</h3>

            <table class="soa-table">
                <tr>
                    <th>Subject</th>
                    <th>Units</th>
                    <th>Other Fees</th>
                </tr>

                <?php 
                $tuition_q = mysqli_query($con,"SELECT fee_amount FROM adminfee WHERE fee_name='Tuition Fee'");
                $tuition_row = mysqli_fetch_assoc($tuition_q);
                $per_unit = $tuition_row['fee_amount'];
                ?>

                <?php 
                $subject_total = 0;

                $comlab_subjects = [];

                foreach($subjects as $sid => $s){
                    foreach($s['fees'] as $f){
                        if(strpos($f['name'], 'Computer Laboratory Fee') !== false){
                            $comlab_subjects[$sid] = $f['amount'];
                        }
                    }
                }

                $highest_comlab_id = null;

                if(!empty($comlab_subjects)){
                    $highest_comlab_id = array_search(max($comlab_subjects), $comlab_subjects);
                }

                // get other comlab fee once
                $other_q = mysqli_query($con, "
                    SELECT fee_amount 
                    FROM adminfee 
                    WHERE fee_name = 'Other Comlab Fee' 
                    LIMIT 1
                ");
                $other = mysqli_fetch_assoc($other_q);
                $other_comlab_fee = $other ? $other['fee_amount'] : 0;

                foreach($subjects as $id => $sub):
                    foreach($sub['fees'] as $f){
                        $feeAmount = $f['amount'];

                        if(strpos($f['name'], 'Computer Laboratory Fee') !== false){

                            if($id == $highest_comlab_id){
                                $feeAmount = $f['amount'];
                            } else {
                                $other_q = mysqli_query($con, "
                                    SELECT fee_amount 
                                    FROM adminfee 
                                    WHERE fee_name = 'Other Comlab Fee' 
                                    LIMIT 1
                                ");
                                $other = mysqli_fetch_assoc($other_q);

                                $feeAmount = $other ? $other['fee_amount'] : 0;
                            }
                        }

                        $subject_total += $feeAmount;
                    }
                endforeach;
                ?>
                <?php foreach($subjects as $id => $sub): ?>
                <tr>
                    <td><?= $sub['code']; ?></td>
                    <td class="center"><?= $sub['units']; ?></td>
                    <td class="right">

                    <?php foreach($sub['fees'] as $f): 

                        $amount = $f['amount'];

                        if(strpos($f['name'], 'Computer Laboratory Fee') !== false){

                            if($id != $highest_comlab_id){
                                $label = 'Other Comlab Fee';
                                $amount = $other_comlab_fee;
                            }
                        }
                    ?>

                    ₱<?= number_format($amount,2); ?><br>

                    <?php endforeach; ?>

                    </td>
                </tr>
                <?php endforeach; ?>
                <tr class="soa-section">
                    <td class="right" >Total Units</td>
                    <td class="center"><?= $total_units; ?></td>
                    <td></td>
                </tr>
            </table>
            <br>
            <?php
            $show_enroll_button = false;

            if (!$enroll && empty($last_sem) && empty($last_sy_id)) {
                // Never enrolled
                $show_enroll_button = true;

            } else {
                // Normalize values
                // check if student is enrolled in CURRENT SY + SEM
$is_currently_enrolled = false;

$check_current = mysqli_query($con, "
    SELECT 1 
    FROM enroll_student 
    WHERE student_id = $student_id 
      AND sy_id = $current_sy_id
    LIMIT 1
");

if ($check_current && mysqli_num_rows($check_current) > 0) {
    $is_currently_enrolled = true;
}

$show_enroll_button = (!$is_currently_enrolled && $remaining_balance <= 0);
            }
            ?>

            <?php if ($show_enroll_button): ?>
            <button class="open-btn"
                onclick="window.location.href='student_enrollment.php?student_id=<?= $student_id ?>'">
                Enroll Student
            </button>
            <?php endif; ?>
        

            </div>

        <!-- RIGHT: COMPUTATION -->
        <div class="computation-section">
            <h3>Computation</h3>

            <table class="soa-table">

                <tr>
                    <td class="right">Tuition Fee</td>
                    <td class="right">₱ <?= number_format($fee['tuition_fee'], 2); ?></td>
                </tr>

                <?php if($discount_percent > 0): ?>
                <tr>
                    <td class="right">Discount (<?= $discount_name ?> - <?= $discount_percent ?>%)</td>
                    <td class="right">₱ <?= number_format($fee['tuition_fee'] - $fee['discounted_tuition_fee'], 2); ?></td>
                </tr>

                <tr>
                    <td class="right">Discounted Tuition Fee</td>
                    <td class="right">₱ <?= number_format($fee['discounted_tuition_fee'], 2); ?></td>
                </tr>
                <?php else: ?>
                <tr>
                    <td class="right">Discounted Tuition Fee</td>
                    <td class="right">₱ <?= number_format($fee['tuition_fee'], 2); ?></td>
                </tr>
                <?php endif; ?>

                <tr>
                    <td class="right">Misc Fee</td>
                    <td class="right">₱ <?= number_format($fee['misc_fee'], 2); ?></td>
                </tr>

                <tr>
                    <td class="right">CWTS Fee</td>
                    <td class="right">₱ <?= number_format($fee['special_fee'], 2); ?></td>
                </tr>

                <tr>
                    <td class="right">Lab Fees</td>
                    <td class="right">₱ <?= number_format($fee['subj_fee'], 2); ?></td>
                </tr>

                <tr class="total-row">
                    <td class="right">TOTAL</td>
                    <td class="right">₱ <?= number_format($fee['total_fee'], 2); ?></td>
                </tr>

                <tr>
                    <td class="right">Down Payment</td>
                    <td class="right">₱ <?= number_format($fee['down_payment'], 2); ?></td>
                </tr>

                <tr class="balance-row">
                    <td class="right">Balance</td>
                    <td class="right">₱ <?= number_format($fee['balance_fee'], 2); ?></td>
                </tr>

                <tr class="total-row">
                    <td class="right">Monthly</td>
                    <td class="right">₱ <?= number_format($fee['monthly_fee'], 2); ?></td>
                </tr>

            </table>
        </div>
        
    </div>
    <?php if ($is_currently_enrolled): ?>
    <div class="monthly-payment-section">
        <h3 style="margin-top:15px;">Monthly Payment Schedule</h3>

        <table class="payment-table">
            <thead>
                <tr>
                    <th>Month</th>
                    <th>Due Date</th>
                    <th>Amount Due</th>
                    <th>Amount Paid</th>
                    <th>Mode</th>
                    <th>Date Paid</th>
                    <th>Status</th>
                </tr>
            </thead>

            <tbody>
            <?php foreach($monthly_payments as $pay): ?>
            <tr>
                <td><?= $pay['month'] ?></td>
                <td><?= $pay['due'] ?></td>
                <td>₱ <?= number_format($pay['amount_due'],2) ?></td>
                <td>₱ <?= number_format($pay['amount_paid'],2) ?></td>
                <td><?= $pay['mode'] ?></td>
                <td>
                    <?php
                    if($pay['date_paid'] != '-') {
                        $date = new DateTime($pay['date_paid'], new DateTimeZone('Asia/Manila'));
                        echo $date->format('M d, Y') . '<br>' . $date->format('g:i A');
                    } else {
                        echo '-';
                    }
                    ?>
                </td>
                <td style="color:
                    <?= $pay['status']=='Paid' ? 'green' :
                        ($pay['status']=='Unpaid' ? 'red' : '#999'); ?>">
                    <?= $pay['status'] ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>

            <tfoot>
                <tr>
                    <td colspan="3"><b>Remaining Balance</b></td>
                    <td colspan="1"><b>₱ <?= number_format($remaining_balance, 2); ?></b></td>
                    <td colspan="3"></td>
                </tr>
            </tfoot>
        </table>
    </div>
<?php endif; ?>

</div>
          

       
        </div>
    
           

      </div>
    </aside>
  </div>

  </div>


    <!-- Script -->
     <script src="../Jscript/script.js"></script>
     <script src="../Jscript/form.js"></script>
</body>
</html>