<?php
session_start();
include('../login/check_flogin.php');

if (!isset($_SESSION['student_id'])) {
    header("Location: ../login/student_login.php");
    exit();
}

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

$student_id = $_SESSION['student_id'];

// Fetch student info
$sql = "SELECT * FROM adminstudent WHERE student_id = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "i", $student_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$student = mysqli_fetch_assoc($result);

// HANDLE SUBMIT RECEIPT
if($_SERVER['REQUEST_METHOD'] === 'POST') {

    if(isset($_FILES['receipt']) && $_FILES['receipt']['error'] == 0) {

        $fileName = $_FILES['receipt']['name'];
        $fileTmp = $_FILES['receipt']['tmp_name'];
        $fileSize = $_FILES['receipt']['size'];

        $fileExt = explode('.', $fileName);
        $fileActualExt = strtolower(end($fileExt));

        $allowed = ['jpg','jpeg','png'];

        if(in_array($fileActualExt, $allowed)) {

            if($fileSize <= 5000000){ // 5MB

                $uploadFolder = '../uploads/student_receipt/pending_payment/';

                if(!is_dir($uploadFolder)){
                    mkdir($uploadFolder, 0777, true);
                }

                $lastName = preg_replace('/[^A-Za-z0-9]/', '', $student['l_name']); 
                $studentNum = $student['student_id_num'];

                $newFileName = $lastName . '_' . $studentNum . '.' . $fileActualExt;
                $fileDestination = $uploadFolder . $newFileName;

                if(move_uploaded_file($fileTmp, $fileDestination)) {

                    $amount = $_POST['amount'];
                    $status = 'Pending';
                    $method = 'Online'; 
                    $insert_sql = "INSERT INTO student_payment 
                        (student_id, spay_amount, spay_image, spay_status, spay_method) 
                        VALUES (?, ?, ?, ?, ?)";

                    $stmt_insert = mysqli_prepare($con, $insert_sql);

                    mysqli_stmt_bind_param($stmt_insert, "idsss", 
                        $student_id, 
                        $amount, 
                        $newFileName, 
                        $status, 
                        $method
                    );

                    mysqli_stmt_execute($stmt_insert);

                    // prevent resubmission
                    $_SESSION['upload_success'] = "Receipt uploaded successfully. Waiting for admin verification.";
                    header("Location: " . $_SERVER['PHP_SELF']);
                    exit();
                }

            } else {
                echo "<script>alert('File too large. Maximum 5MB');</script>";
            }

        } else {
            echo "<script>alert('Only JPG, JPEG, PNG allowed');</script>";
        }
    }
}
?>

<!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> Dashboard - Student </title>

    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    <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/snavstyle.css">

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

    body{
        background: #F3F4F4;
    }

    .mainbar {
        margin-left: 270px; 
        flex: 1;
        padding: 10px;
        transition: all 0.4s ease;
        overflow-y: auto;
    }

    .mainbar-header {
        padding: 6px 12px;
        background-color: #3e7f31;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .mainbar-header h1 {
        margin: 0;
        color: white;
        font-size: 18px;
    }

    .container {
        width: 100%;                 
        max-width: 500px;            
        min-height: 300px;  
        background-color: #4a9c3f;
        border-radius: 10px;
        display: flex;
        justify-content: center;     
        align-items: center;         
        margin: 50px auto;              
        box-sizing: border-box;
        padding: 20px; 
    }

    .form {
        background-color: white;
        padding: 20px; 
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        text-align: left;
        margin: 0; 
        max-width: 500px;    
        width: 100%;
        box-sizing: border-box;
    }

    .form label {
        font-size: 11px;
    }

    .form input[type="number"],
    .form input[type="file"] {
        width: 100%;
        padding: 6px 12px;
        margin-top: 5px;
        margin-bottom: 5px;
        border-radius: 6px;
        border: 1px solid #ccc;
        font-size: 11px;
    }

    .form button {
        width: 20%;
        padding: 6px;
        background-color: #4CAF50;
        color: white;
        font-size: 11px;
        font-weight: 600;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        display: block;       
        margin: 5px auto 0;  
    }

    .form button:hover {
        background-color: #43a047;
    }

    .form p {
        text-align: left;
        margin-top: 15px;
        font-size: 11px; 
        color: #303030;
    }

.modal {
    display: none; 
    position: fixed;
    z-index: 10000;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    font-size: 11px; 
    background-color: rgba(0,0,0,0.5);

    justify-content: center;
    align-items: center;
}

.modal-content {
    background: white;
    width: 100%;
    max-width: 350px;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
}

.modal-content h2 {
    font-size:11px;
    font-weight: 600;
}

.modal-content p {
    margin: 10px;
}

.modal-buttons {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    flex-wrap: nowrap;
}

.modal-buttons .btn-save,
.modal-buttons .btn-cancel {
    min-width: 90px;  
    padding: 5px 10px;
    font-size: 11px;
    font-weight: 600;
    margin: 0;             
}

        .modal-buttons .btn-save {
            background-color: #4CAF50;
            color: white;
        }

        .modal-buttons .btn-cancel {
            background-color: #ccc;
            color: #333;
        }

        .modal-buttons .btn-cancel:hover {
            background-color: #e0e0e0;
        }

.success-message {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
    padding: 3px 6px;
    border-radius: 10px;
    margin: 5px auto 5px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 6px;
    font-size: 11px;
    white-space: nowrap;      
    overflow: hidden;
    text-overflow: ellipsis;  
}

.success-message ion-icon {
    font-size: 16px;
    flex-shrink: 0;
}

@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

    /* Tablets */
@media screen and (max-width: 768px) {
    .mainbar {
        margin-left: 0;
        padding: 8px;
        margin-top: 60px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 16px;
        text-align: center;
    }

    .container {
        padding: 6px;
        margin: 15px auto;
        max-width: 80%;
    }

    .form {
        padding: 10px 20px;
        max-width: 100%;
    }

    .form input[type="text"],
    .form input[type="file"] {
        height: 30px;
        font-size: 10px;
        padding: 6px;
    }

    .form button {
        width: 30%;
        padding: 6px;
        font-size: 10px;
        font-weight: 600;
    }

    .form p {
        font-size: 10px;
    }
}

/* Mobile phones */
@media screen and (max-width: 576px) {
    .mainbar {
        margin-top: 50px;
        padding: 10px;
    }

    .mainbar-header {
        padding: 5px 10px;
        border-radius: 8px;
    }

    .mainbar-header h1 {
        font-size: 14px;
        text-align: center;
    }

    .container {
        padding: 10px;
        margin: 20px auto;
        border-radius: 8px;
    }

    .form {
        padding: 20px 20px;
        border-radius: 8px;
        margin: 15px auto;
    }

    .form label {
        font-size: 8px;
    }

    .form input[type="text"],
    .form input[type="file"] {
        height: 25px;
        padding: 6px;
        font-size: 8px;
        margin-bottom: 10px;
    }

    .form button {
        width: 25%;
        padding: 6px;
        font-size: 8px;
        margin-top: 10px;
    }

    .form p {
        font-size: 8px;
        margin-top: 15px;
    }
}

/* Small phones */
@media screen and (max-width: 400px) {
    .mainbar-header h1 {
        font-size: 12px;
        text-align: center;
    }

    .form {
        padding: 15px 15px;
    }

    .form label {
        font-size: 6px;
    }

    .form input[type="text"],
    .form input[type="file"] {
        height: 20px;
        font-size: 6px;
        padding: 6px;
    }

    .form button {
        width: 20%;
        padding: 6px;
        font-size: 6px;
    }

    .form p {
        font-size: 6px;
    }
}
</style>

</head>
<body>
    <!-- Side Navigation -->
    <?php include('studentnav.php'); ?>
    <!-- MAIN -->
    <aside class="mainbar">
        <div class="mainbar-header">
            <h1> Settle Payment </h1>
        </div>
        <div class="container">
            <div class="form">
                <?php if (isset($_SESSION['upload_success'])): ?>
                    <div class="success-message" id="successMessage">
                        <ion-icon name="checkmark-circle-outline"></ion-icon>
                        <span><?php echo $_SESSION['upload_success']; ?></span>
                    </div>
                <?php unset($_SESSION['upload_success']); ?>
                <?php endif; ?>
                <form id="receiptForm" action="" method="post" enctype="multipart/form-data">
                    <label for="amount"> Amount </label><br>
                    <input type="number" id="amount" name="amount" placeholder="Enter amount" required><br>

                    <label for="receipt"> Upload Receipt Photo </label><br>
                    <input type="file" id="receipt" name="receipt" accept=".jpg,.jpeg,.png" required><br>
            
                    <button type="button" onclick="openConfirmModal()"> Submit </button>
                </form>

                <div id="confirmModal" class="modal">
                    <div class="modal-content">
                        <h2> CONFIRM SUBMISSION </h2>

                        <p style="font-size:11px; text-align:center;">
                            Are you sure you want to submit this receipt?<br>
                            Please review before confirming.
                        </p>

                        <div class="modal-buttons">
                            <button type="button" class="btn-save" onclick="submitReceipt()"> Confirm </button>
                            <button type="button" class="btn-cancel" onclick="closeConfirmModal()"> Cancel </button>
                        </div>
                    </div>
                </div>

                <p>
                    <strong> Note: </strong> <br>
                    <strong> 1 file </strong> per transaction <br>
                    Please upload a receipt in <strong> JPEG, JPG, or PNG </strong> format. <br>
                    Maximum file size: <strong> 5 MB </strong>.
                </p>
            </div>
        </div>
    </aside>

<script>
function openConfirmModal() {
    document.getElementById('confirmModal').style.display = 'flex';
}
function closeConfirmModal() {
    document.getElementById('confirmModal').style.display = 'none';
}
function submitReceipt() {
    let form = document.getElementById('receiptForm');

    // prevent duplicate hidden inputs
    if (!form.querySelector('input[name="submit_receipt"]')) {
        let input = document.createElement("input");
        input.type = "hidden";
        input.name = "submit_receipt";
        input.value = "1";
        form.appendChild(input);
    }

    form.submit();
}
</script>

    <script>
    // This is for how many secs. the success msg will appear on the screen
    setTimeout(function() {
        const msg = document.getElementById("successMessage");
        if (msg) {
            msg.style.transition = "opacity 0.5s";
            msg.style.opacity = "0";

            setTimeout(function(){
                msg.remove();
            }, 500);
        }
    }, 3000);
    </script>
    
     <!-- ionicons source -->
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
</body>
</html>