<?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 delete request
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $deposit_id = intval($_GET['delete']);
    
    try {
        // Get student ID first
        $query = "SELECT student_id FROM fee_history WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$deposit_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            // Delete the deposit record
            $delete_query = "DELETE FROM fee_history WHERE id = ?";
            $delete_stmt = $db->prepare($delete_query);
            $delete_stmt->execute([$deposit_id]);
            
            // 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([$result['student_id'], $result['student_id']]);
            
            $_SESSION['success_message'] = 'Fee deposit record deleted successfully!';
        } else {
            $_SESSION['error_message'] = 'Deposit record not found!';
        }
    } catch (PDOException $e) {
        $_SESSION['error_message'] = 'Failed to delete deposit record!';
    }
    
    redirect('fee_history.php');
}

// Get search term
$search_term = isset($_GET['search']) ? sanitizeInput($_GET['search']) : '';

// Get fee history data
if (!empty($search_term)) {
    $query = "SELECT fh.*, s.student_name, s.student_id as student_code, s.total_fee
              FROM fee_history fh 
              JOIN students s ON fh.student_id = s.id 
              WHERE s.student_name LIKE :search_term 
              OR s.student_id LIKE :search_term 
              OR fh.payment_method LIKE :search_term
              ORDER BY fh.payment_date DESC";
    $stmt = $db->prepare($query);
    $search_term_param = "%{$search_term}%";
    $stmt->bindParam(':search_term', $search_term_param);
    $stmt->execute();
} else {
    $query = "SELECT fh.*, s.student_name, s.student_id as student_code, s.total_fee
              FROM fee_history fh 
              JOIN students s ON fh.student_id = s.id 
              ORDER BY fh.payment_date DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
}

$deposits = $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 History - <?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">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.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;
        }
        .table-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .search-box {
            border-radius: 25px;
            border: 2px solid #e9ecef;
            padding: 10px 20px;
            transition: all 0.3s ease;
        }
        .search-box:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
        }
        .btn-action {
            padding: 6px 12px;
            margin: 2px;
            border-radius: 6px;
            font-size: 12px;
        }
    </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" href="fee_deposit.php">
                                <i class="fas fa-credit-card me-2"></i>Fee Deposit
                            </a>
                            <a class="nav-link active" 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 History</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">
                        <!-- Fee History Table -->
                        <div class="table-container">
                            <div class="p-3 border-bottom">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h5 class="mb-0">
                                            <i class="fas fa-history me-2"></i>Fee Deposit History
                                        </h5>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="d-flex justify-content-end">
                                            <form method="GET" class="d-flex me-3">
                                                <input type="text" class="form-control search-box" name="search" 
                                                       placeholder="Search deposits..." value="<?php echo $search_term; ?>">
                                                <button type="submit" class="btn btn-outline-primary ms-2">
                                                    <i class="fas fa-search"></i>
                                                </button>
                                            </form>
                                            <a href="fee_deposit.php" class="btn btn-primary">
                                                <i class="fas fa-plus me-2"></i>New Deposit
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-hover mb-0" id="depositsTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Receipt No</th>
                                            <th>Student Name</th>
                                            <th>Student ID</th>
                                            <th>Payment Date</th>
                                            <th>Amount</th>
                                            <th>Method</th>
                                            <th>Next Payment</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($deposits as $deposit): ?>
                                        <tr>
                                            <td>
                                                <strong>INV-<?php echo date('Y', strtotime($deposit['payment_date'])); ?>-<?php echo str_pad($deposit['id'], 4, '0', STR_PAD_LEFT); ?></strong>
                                            </td>
                                            <td><?php echo $deposit['student_name']; ?></td>
                                            <td><?php echo $deposit['student_code']; ?></td>
                                            <td><?php echo formatDate($deposit['payment_date']); ?></td>
                                            <td>
                                                <span class="badge bg-success">₹<?php echo number_format($deposit['amount'], 2); ?></span>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo $deposit['payment_method']; ?></span>
                                            </td>
                                            <td>
                                                <?php if ($deposit['next_payment_date']): ?>
                                                    <?php echo formatDate($deposit['next_payment_date']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="invoice_pdf.php?id=<?php echo $deposit['id']; ?>" 
                                                   class="btn btn-sm btn-outline-primary btn-action" target="_blank">
                                                    <i class="fas fa-file-pdf"></i> Receipt
                                                </a>
                                                <a href="?delete=<?php echo $deposit['id']; ?>" 
                                                   class="btn btn-sm btn-outline-danger btn-action"
                                                   onclick="return confirm('Are you sure you want to delete this deposit record?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="toast show" role="alert">
                <div class="toast-header bg-success text-white">
                    <i class="fas fa-check-circle me-2"></i>
                    <strong class="me-auto">Success</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="toast show" role="alert">
                <div class="toast-header bg-danger text-white">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong class="me-auto">Error</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#depositsTable').DataTable({
                "pageLength": 25,
                "order": [[3, "desc"]], // Sort by payment date
                "columnDefs": [
                    { "orderable": false, "targets": 7 }
                ]
            });
        });
    </script>
</body>
</html>
