<?php
require_once 'config/config.php';
require_once 'config/database.php';
require_once 'models/Student.php';

requireLogin();

$database = new Database();
$db = $database->getConnection();
$student = new Student($db);

$error_message = '';
$success_message = '';

// Handle fee deposit
if ($_POST && isset($_POST['deposit_fee'])) {
    $student_id = intval($_POST['student_id']);
    $amount = floatval($_POST['amount']);
    $payment_date = $_POST['payment_date'];
    $next_payment_date = !empty($_POST['next_payment_date']) ? $_POST['next_payment_date'] : null;
    $payment_method = $_POST['payment_method'];
    $description = sanitizeInput($_POST['description']);

    if ($student_id > 0 && $amount > 0 && !empty($payment_date)) {
        try {
            // Insert fee deposit record
            $query = "INSERT INTO fee_history (student_id, amount, payment_date, next_payment_date, payment_method, description) 
                      VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $db->prepare($query);
            $stmt->execute([$student_id, $amount, $payment_date, $next_payment_date, $payment_method, $description]);

            // Get the inserted deposit ID
            $deposit_id = $db->lastInsertId();

            // Update student's total deposited amount
            $update_query = "UPDATE students SET fees_deposit = (
                                SELECT COALESCE(SUM(amount), 0) FROM fee_history WHERE student_id = ?
                            ) WHERE id = ?";
            $update_stmt = $db->prepare($update_query);
            $update_stmt->execute([$student_id, $student_id]);

            $success_message = 'Fee deposit recorded successfully! <a href="invoice_pdf.php?id=' . $deposit_id . '" target="_blank" class="alert-link">Generate Receipt</a>';
        } catch (PDOException $e) {
            $error_message = 'Failed to record fee deposit: ' . $e->getMessage();
        }
    } else {
        $error_message = 'Please fill in all required fields!';
    }
}

// Get all students for dropdown
$students_query = "SELECT id, student_name, student_id, total_fee, fees_deposit FROM students WHERE status = 'Active' ORDER BY student_name";
$students_stmt = $db->prepare($students_query);
$students_stmt->execute();
$students = $students_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fee Deposit - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .form-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .form-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem;
        }
        .form-control, .form-select {
            border-radius: 8px;
            border: 2px solid #e9ecef;
            padding: 10px 15px;
            transition: all 0.3s ease;
        }
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-submit {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 8px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .required {
            color: #dc3545;
        }
        .student-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar">
                    <div class="p-3">
                        <h4 class="text-center mb-4">
                            <i class="fas fa-graduation-cap me-2"></i>
                            <?php echo APP_NAME; ?>
                        </h4>
                        <nav class="nav flex-column">
                            <a class="nav-link" href="index.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                            <a class="nav-link" href="add_student.php">
                                <i class="fas fa-user-plus me-2"></i>Add Student
                            </a>
                            <a class="nav-link active" href="fee_deposit.php">
                                <i class="fas fa-credit-card me-2"></i>Fee Deposit
                            </a>
                            <a class="nav-link" href="fee_history.php">
                                <i class="fas fa-history me-2"></i>Fee History
                            </a>
                            <a class="nav-link" href="student_info.php">
                                <i class="fas fa-info-circle me-2"></i>Student Info
                            </a>
                            <a class="nav-link" href="reports.php">
                                <i class="fas fa-chart-bar me-2"></i>Reports
                            </a>
                            <a class="nav-link" href="settings.php">
                                <i class="fas fa-cog me-2"></i>Settings
                            </a>
                            <hr class="my-3">
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt me-2"></i>Logout
                            </a>
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 px-0">
                <div class="main-content">
                    <!-- Top Navigation -->
                    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
                        <div class="container-fluid">
                            <span class="navbar-brand mb-0 h1">Fee Deposit</span>
                            <div class="d-flex align-items-center">
                                <span class="me-3">Welcome, <?php echo $_SESSION['admin_name']; ?></span>
                                <div class="dropdown">
                                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-user-circle"></i>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i>Profile</a></li>
                                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </nav>

                    <div class="p-4">
                        <div class="row justify-content-center">
                            <div class="col-lg-8">
                                <div class="form-container">
                                    <div class="form-header">
                                        <h4 class="mb-0">
                                            <i class="fas fa-credit-card me-2"></i>Fee Deposit
                                        </h4>
                                        <p class="mb-0">Record student fee installment</p>
                                    </div>

                                    <div class="p-4">
                                        <?php if ($error_message): ?>
                                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                <?php echo $error_message; ?>
                                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                            </div>
                                        <?php endif; ?>

                                        <?php if ($success_message): ?>
                                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                                <i class="fas fa-check-circle me-2"></i>
                                                <?php echo $success_message; ?>
                                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Student Info Display -->
                                        <div class="student-info" id="studentInfo">
                                            <h6 class="text-primary mb-3">Selected Student Information</h6>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <strong>Student ID:</strong> <span id="selectedStudentId"></span><br>
                                                    <strong>Name:</strong> <span id="selectedStudentName"></span>
                                                </div>
                                                <div class="col-md-6">
                                                    <strong>Total Fee:</strong> <span id="selectedTotalFee"></span><br>
                                                    <strong>Deposited:</strong> <span id="selectedDeposited"></span><br>
                                                    <strong>Pending:</strong> <span id="selectedPending"></span>
                                                </div>
                                            </div>
                                        </div>

                                        <form method="POST" action="">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="student_id" class="form-label">Select Student <span class="required">*</span></label>
                                                    <select class="form-select" id="student_id" name="student_id" required onchange="showStudentInfo()">
                                                        <option value="">Choose a student...</option>
                                                        <?php foreach ($students as $student): ?>
                                                        <option value="<?php echo $student['id']; ?>" 
                                                                data-name="<?php echo $student['student_name']; ?>"
                                                                data-student-id="<?php echo $student['student_id']; ?>"
                                                                data-total-fee="<?php echo $student['total_fee']; ?>"
                                                                data-deposited="<?php echo $student['fees_deposit']; ?>">
                                                            <?php echo $student['student_name']; ?> (<?php echo $student['student_id']; ?>)
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="payment_date" class="form-label">Deposit Date <span class="required">*</span></label>
                                                    <input type="date" class="form-control" id="payment_date" name="payment_date" 
                                                           value="<?php echo date('Y-m-d'); ?>" required>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="next_payment_date" class="form-label">Next Payment Date</label>
                                                    <input type="date" class="form-control" id="next_payment_date" name="next_payment_date">
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="amount" class="form-label">Deposit Amount <span class="required">*</span></label>
                                                    <input type="number" class="form-control" id="amount" name="amount" 
                                                           step="0.01" min="0" required>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="payment_method" class="form-label">Payment Method</label>
                                                    <select class="form-select" id="payment_method" name="payment_method">
                                                        <option value="Cash">Cash</option>
                                                        <option value="Bank Transfer">Bank Transfer</option>
                                                        <option value="Cheque">Cheque</option>
                                                        <option value="Online">Online</option>
                                                    </select>
                                                </div>

                                                <div class="col-12 mb-3">
                                                    <label for="description" class="form-label">Description</label>
                                                    <textarea class="form-control" id="description" name="description" rows="3" 
                                                              placeholder="Optional description for this payment..."></textarea>
                                                </div>
                                            </div>

                                            <div class="d-flex justify-content-end mt-4">
                                                <a href="index.php" class="btn btn-secondary me-3">
                                                    <i class="fas fa-times me-2"></i>Cancel
                                                </a>
                                                <button type="submit" name="deposit_fee" class="btn btn-primary btn-submit">
                                                    <i class="fas fa-save me-2"></i>Record Deposit
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function showStudentInfo() {
            const select = document.getElementById('student_id');
            const selectedOption = select.options[select.selectedIndex];
            const studentInfo = document.getElementById('studentInfo');
            
            if (select.value) {
                const name = selectedOption.getAttribute('data-name');
                const studentId = selectedOption.getAttribute('data-student-id');
                const totalFee = parseFloat(selectedOption.getAttribute('data-total-fee'));
                const deposited = parseFloat(selectedOption.getAttribute('data-deposited'));
                const pending = totalFee - deposited;
                
                document.getElementById('selectedStudentId').textContent = studentId;
                document.getElementById('selectedStudentName').textContent = name;
                document.getElementById('selectedTotalFee').textContent = '₹' + totalFee.toFixed(2);
                document.getElementById('selectedDeposited').textContent = '₹' + deposited.toFixed(2);
                document.getElementById('selectedPending').textContent = '₹' + pending.toFixed(2);
                
                studentInfo.style.display = 'block';
            } else {
                studentInfo.style.display = 'none';
            }
        }
    </script>
</body>
</html>
