<?php
include('includes/session.php');
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';

error_reporting(0);

require_once 'vendor/autoload.php';
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Resolve system session/term for header badges only
$_st = resolveCurrentSessionTerm($con);
$currentSession = $_st['session_name'];
$currentTerm    = $_st['term_name'];

// Get student info
$student_id = $_SESSION['student_id'];
$stmt = $con->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("s", $student_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
$stream      = $row['stream'];
$studentname = $row['studentName'];
$repeat      = $row['demote_status'];
$class       = $row['class'];

// Default state — always show selection form
$step               = 'selection';
$currentSessionId   = '';
$currentSessionName = '';
$currentTermId      = '';
$currentTermName    = '';

// --- HANDLE FORM SUBMISSION ---
if (isset($_POST['btn_select_session'])) {
    $sel_session_id = (int) $_POST['session_id'];
    $sel_term_id    = (int) $_POST['term_id'];
    $class          = $_POST['class'];

    $sessQ = $con->prepare("SELECT session_name FROM school_sessions WHERE id = ?");
    $sessQ->bind_param("i", $sel_session_id);
    $sessQ->execute();
    $currentSessionName = $sessQ->get_result()->fetch_assoc()['session_name'] ?? '';
    $sessQ->close();

    $termQ = $con->prepare("SELECT term_name FROM school_terms WHERE id = ?");
    $termQ->bind_param("i", $sel_term_id);
    $termQ->execute();
    $currentTermName = $termQ->get_result()->fetch_assoc()['term_name'] ?? '';
    $termQ->close();

    $currentSessionId = $sel_session_id;
    $currentTermId    = $sel_term_id;

    // --- PAYMENT CHECK ---
    $step = 'ready'; // assume paid unless proven otherwise

    $PaidStmt = $con->prepare("SELECT pay_for FROM payment 
        WHERE student_id = ? AND class = ? AND school_type = ?
        AND session = ? AND Term = ? AND pay_for LIKE 'School Fees%' LIMIT 1");
    $PaidStmt->bind_param("issss", $student_id, $class, $stream, $currentSessionName, $currentTermName);
    $PaidStmt->execute();
    $pay_for = $PaidStmt->get_result()->fetch_assoc()['pay_for'] ?? '';

    $student_type = ($pay_for == 'School Fees (New Student)') ? "New" : "Old";

    $feeQuery = "SELECT amount FROM fee_records 
        WHERE class = ? AND stream = ? AND name = ? AND student_type = ? AND session = ? AND term = ? 
        ORDER BY created_at DESC LIMIT 1";
    $feeStmt = $con->prepare($feeQuery);
    $feeStmt->bind_param("ssssss", $class, $stream, $pay_for, $student_type, $currentSessionName, $currentTermName);
    $feeStmt->execute();
    $currentTermTotalFees = $feeStmt->get_result()->fetch_assoc()['amount'] ?? 0;

    if (trim($class) === 'SS 1' && $repeat === 1 && $currentTermName === 'First Term') {
        $feeStmt = $con->prepare($feeQuery);
        $feeStmt->bind_param("ssssss", $class, $stream, $pay_for, $student_type, $currentSessionName, $currentTermName);
        $feeStmt->execute();
        $currentTermTotalFees = $feeStmt->get_result()->fetch_assoc()['amount'] ?? $currentTermTotalFees;
    }

    if ($currentTermName === 'First Term' && in_array($class, ['JSS 3', 'SS 1', 'SS 3'])) {
        $special_fee_names = [
            'JSS 3' => 'First Term JSS 3 School Fees',
            'SS 1'  => 'First Term SS 1 School Fees',
            'SS 3'  => 'First Term SS 3 School Fees',
        ];
        $special_fee_name = $special_fee_names[$class];
        $sFeeAmt = 0.0;
        $sFeeQ = $con->prepare("SELECT amount FROM fee_records WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? AND session = ? AND term = 'First Term' ORDER BY id DESC LIMIT 1");
        $sFeeQ->bind_param("ssss", $class, $stream, $special_fee_name, $currentSessionName);
        $sFeeQ->execute();
        $sFeeRes = $sFeeQ->get_result()->fetch_assoc();
        $sFeeQ->close();
        if ($sFeeRes && (float)$sFeeRes['amount'] > 0) {
            $sFeeAmt = (float)$sFeeRes['amount'];
        } else {
            $sFeeQ2 = $con->prepare("SELECT amount FROM fees WHERE class = ? AND stream = ? AND student_type = 'Old' AND name = ? LIMIT 1");
            $sFeeQ2->bind_param("sss", $class, $stream, $special_fee_name);
            $sFeeQ2->execute();
            $sFeeRes2 = $sFeeQ2->get_result()->fetch_assoc();
            $sFeeQ2->close();
            if ($sFeeRes2) $sFeeAmt = (float)$sFeeRes2['amount'];
        }
        if ($sFeeAmt > 0) $currentTermTotalFees = $sFeeAmt;
    }

    if (in_array($currentTermName, ['Second Term', 'Third Term']) && in_array($class, ['JSS 3', 'SS 3'])) {
        $feeStmt = $con->prepare($feeQuery);
        $feeStmt->bind_param("ssssss", $class, $stream, $pay_for, $student_type, $currentSessionName, $currentTermName);
        $feeStmt->execute();
        $currentTermTotalFees = ($feeStmt->get_result()->fetch_assoc()['amount'] ?? 0) * 2;
    }

    $paidStmt = $con->prepare("SELECT SUM(amount) as total_paid FROM payment 
        WHERE student_id = ? AND class = ? AND pay_for = ? AND school_type = ? AND session = ? AND Term = ?");
    $paidStmt->bind_param("isssss", $student_id, $class, $pay_for, $stream, $currentSessionName, $currentTermName);
    $paidStmt->execute();
    $totalPaidAmount = $paidStmt->get_result()->fetch_assoc()['total_paid'] ?? 0;

    if (($pay_for == '' && $totalPaidAmount == 0) || $totalPaidAmount < $currentTermTotalFees) {
        $step = 'check_payment';
    }

    // --- REDIRECT IF PAID ---
    if ($step === 'ready') {
        header("Location: view_result.php?session_id=$currentSessionId&term_id=$currentTermId&tab_id=$tabSessionID&class=$class");
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include('includes/headerstd.php'); ?>
        <?php include('includes/sidebaroldstd.php'); ?>

        <div class="content-wrapper">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-clipboard-list"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Result Management
                                            <span class="premium-subtitle text-secondary">View Result</span>
                                        </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSession): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i>
                                                    <?= htmlspecialchars($currentSession) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTerm): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i>
                                                    <?= htmlspecialchars($currentTerm) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="oldstdday.php" class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">View Result</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="content">
                <div class="container-fluid">
                    <div class="card shadow-sm">
                        <div class="card-header bg-primary text-white">
                            <h5 class="card-title font-weight-bold">
                                <i class="fas fa-file-alt"></i> Check Result
                            </h5>
                        </div>
                        <div class="card-body">

                            <?php if ($step === 'selection'): ?>
                                <form method="post">
                                    <div class="row">
                                        <div class="col-md-6 offset-md-3">
                                            <p class="text-center">Please select the Session, Term and Class you wish to view.</p>

                                            <div class="form-group">
                                                <label>Session</label>
                                                <select name="session_id" class="form-control" required>
                                                    <option value="">Select Session</option>
                                                    <?php
                                                    $rss = $con->query("SELECT * FROM school_sessions ORDER BY start_date DESC");
                                                    while ($rows = $rss->fetch_assoc()):
                                                    ?>
                                                        <option value="<?= $rows['id'] ?>"><?= htmlspecialchars($rows['session_name']) ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label>Term</label>
                                                <select name="term_id" class="form-control" required>
                                                    <option value="">Select Term</option>
                                                    <?php
                                                    $rst = $con->query("SELECT * FROM school_terms GROUP BY term_name ORDER BY start_date ASC");
                                                    while ($rowt = $rst->fetch_assoc()):
                                                    ?>
                                                        <option value="<?= $rowt['id'] ?>"><?= htmlspecialchars($rowt['term_name']) ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label for="class">Class</label>
                                                <select name="class" id="class" class="form-control" required>
                                                    <option value="">-- Select Class --</option>
                                                    <?php
                                                    $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");
                                                    while ($rowc = $classResult->fetch_assoc()):
                                                    ?>
                                                        <option value="<?= htmlspecialchars($rowc['class']) ?>"><?= htmlspecialchars($rowc['class']) ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>

                                            <div class="form-group text-center mt-4">
                                                <button type="submit" name="btn_select_session" class="btn btn-primary px-5">
                                                    View Result <i class="fas fa-arrow-right"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>

                            <?php elseif ($step === 'check_payment'): ?>
                                <div class="text-center">
                                    <p><strong>Session:</strong> <?= htmlspecialchars($currentSessionName) ?> &nbsp;|&nbsp;
                                       <strong>Term:</strong> <?= htmlspecialchars($currentTermName) ?></p>
                                    <hr>
                                    <p style="color: red;">Sorry, unable to view results! <br>
                                        Please make sure your school fees are fully paid before you can view your result.</p>
                                    <a href="payschoolfees.php" class="btn btn-primary">
                                        <i class="fas fa-sign-in-alt"></i> Go to School Fees Payment Page
                                    </a>
                                    <br><br>
                                    <a href="verify_email_otp.php" class="btn btn-secondary">
                                        <i class="fas fa-arrow-left"></i> Select Different Session
                                    </a>
                                </div>
                            <?php endif; ?>

                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <?php include('includes/footer.php'); ?>
    <?php include('includes/foot.php'); ?>
    <script>
        $(document).ready(function () {
            $('select').select2({});
        });
    </script>
</body>
</html>
