<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin = $_SESSION['email'];
$userrole = $_SESSION['role'];
$intake = $_SESSION['department'];

if (isset($_SESSION['email'])) {
    // Finance-specific data
    if ($userrole == "Finance") {
        // Get balances (invoices)
        $balances = mysqli_query($conn, "SELECT `id`, `fee_type`, `amount`, `intake`, `period`, `year`, `program` FROM `balances` ORDER BY id DESC");
        
        // Get payments
        $payments = mysqli_query($conn, "SELECT `id`, `payid`, `fee_type`, `studentid`, `amount`, `intake`, `mobile`, `year`, `status`, `paidday`, `period` FROM `payments` ORDER BY id DESC");
        
        // Calculate totals
        $total_revenue = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM payments WHERE status='success'"))['total'];
        $pending_payments = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM payments WHERE status='pending'"))['count'];
        $total_invoices = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM balances"))['count'];
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finance Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: var(--primary);
            --primary-dark: #1a6b4e;
            --primary-light: #34a380;
            --secondary: #2c3e50;
            --accent: #ff6b6b;
            --text: #2d3748;
            --text-light: #718096;
            --bg-light: #f8fafc;
            --border: #e2e8f0;
            --success: #38a169;
            --warning: #d69e2e;
            --danger: #e53e3e;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-light);
            color: var(--text);
            line-height: 1.6;
        }

        .finance-header {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            padding: 2rem;
            margin-bottom: 2rem;
            border-radius: 0 0 15px 15px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            text-align: center;
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin: 0 auto 1rem;
        }

        .revenue .stat-icon { background: rgba(56, 161, 105, 0.1); color: var(--success); }
        .invoices .stat-icon { background: rgba(214, 158, 46, 0.1); color: var(--warning); }
        .pending .stat-icon { background: rgba(229, 62, 62, 0.1); color: var(--danger); }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: var(--text-light);
            font-weight: 500;
        }

        .finance-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            color: var(--secondary);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }

        .table th {
            background: var(--primary-light);
            color: white;
            font-weight: 600;
            border: none;
        }

        .table td {
            vertical-align: middle;
            border-color: var(--border);
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-success { background: rgba(56, 161, 105, 0.1); color: var(--success); }
        .status-pending { background: rgba(214, 158, 46, 0.1); color: var(--warning); }
        .status-failed { background: rgba(229, 62, 62, 0.1); color: var(--danger); }

        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.875rem;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .btn-view { background: rgba(52, 163, 128, 0.1); color: var(--primary); }
        .btn-view:hover { background: var(--primary); color: white; }

        .btn-edit { background: rgba(214, 158, 46, 0.1); color: var(--warning); }
        .btn-edit:hover { background: var(--warning); color: white; }

        .export-btns {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .export-btn {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-excel { background: rgba(33, 150, 83, 0.1); color: #217953; }
        .btn-excel:hover { background: #217953; color: white; }

        .btn-pdf { background: rgba(229, 62, 62, 0.1); color: var(--danger); }
        .btn-pdf:hover { background: var(--danger); color: white; }

        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .finance-header {
                padding: 1.5rem;
            }
            
            .export-btns {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <div class="finance-header">
        <div class="container">
            <h1 class="display-5 fw-bold"><i class="fas fa-money-bill-wave me-3"></i>Finance Dashboard</h1>
            <p class="lead">Manage invoices, payments, and financial records</p>
        </div>
    </div>

    <div class="container">
        <?php if ($userrole == "Finance"): ?>
        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card revenue">
                <div class="stat-icon">
                    <i class="fas fa-money-bill"></i>
                </div>
                <div class="stat-value">K<?php echo number_format($total_revenue, 2); ?></div>
                <div class="stat-label">Total Revenue</div>
            </div>

            <div class="stat-card invoices">
                <div class="stat-icon">
                    <i class="fas fa-file-invoice"></i>
                </div>
                <div class="stat-value"><?php echo number_format($total_invoices); ?></div>
                <div class="stat-label">Total Invoices</div>
            </div>

            <div class="stat-card pending">
                <div class="stat-icon">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-value"><?php echo number_format($pending_payments); ?></div>
                <div class="stat-label">Pending Payments</div>
            </div>
        </div>

        <!-- Export Buttons -->
        <div class="export-btns">
            <a href="export_finance.php?type=excel" class="export-btn btn-excel">
                <i class="fas fa-file-excel"></i> Export to Excel
            </a>
            <a href="export_finance.php?type=pdf" class="export-btn btn-pdf">
                <i class="fas fa-file-pdf"></i> Export to PDF
            </a>
        </div>

        <!-- Invoices Section -->
        <div class="finance-section">
            <h3 class="section-title">
                <i class="fas fa-file-invoice-dollar"></i> Invoices
            </h3>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Fee Type</th>
                            <th>Amount</th>
                            <th>Program</th>
                            <th>Intake</th>
                            <th>Period</th>
                            <th>Year</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($invoice = mysqli_fetch_assoc($balances)): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($invoice['fee_type']); ?></td>
                            <td>K<?php echo number_format($invoice['amount'], 2); ?></td>
                            <td><?php echo htmlspecialchars($invoice['program']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['intake']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['period']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['year']); ?></td>
                            <td>
                                <a href="view_invoice.php?id=<?php echo $invoice['id']; ?>" class="action-btn btn-view">
                                    <i class="fas fa-eye"></i> View
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Payments Section -->
        <div class="finance-section">
            <h3 class="section-title">
                <i class="fas fa-credit-card"></i> Payment Records
            </h3>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Payment ID</th>
                            <th>Student ID</th>
                            <th>Fee Type</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($payment = mysqli_fetch_assoc($payments)): 
                            $status_class = '';
                            switch($payment['status']) {
                                case 'success': $status_class = 'status-success'; break;
                                case 'pending': $status_class = 'status-pending'; break;
                                case 'failed': $status_class = 'status-failed'; break;
                            }
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($payment['payid']); ?></td>
                            <td><?php echo htmlspecialchars($payment['studentid']); ?></td>
                            <td><?php echo htmlspecialchars($payment['fee_type']); ?></td>
                            <td>K<?php echo number_format($payment['amount'], 2); ?></td>
                            <td>
                                <span class="status-badge <?php echo $status_class; ?>">
                                    <?php echo ucfirst($payment['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('M j, Y', strtotime($payment['paidday'])); ?></td>
                            <td>
                                <a href="payment_details.php?id=<?php echo $payment['id']; ?>" class="action-btn btn-view">
                                    <i class="fas fa-eye"></i> Details
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php else: ?>
        <!-- Show access denied message for non-finance users -->
        <div class="alert alert-danger text-center">
            <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
            <h3>Access Denied</h3>
            <p>You don't have permission to access the finance dashboard.</p>
            <a href="dashboard.php" class="btn btn-primary mt-2">Return to Dashboard</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Simple search functionality
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                const filter = this.value.toLowerCase();
                const tables = document.querySelectorAll('.table-responsive table');
                
                tables.forEach(table => {
                    const rows = table.querySelectorAll('tbody tr');
                    rows.forEach(row => {
                        const text = row.textContent.toLowerCase();
                        row.style.display = text.includes(filter) ? '' : 'none';
                    });
                });
            });
        }
    });
</script>
</body>
</html>
<?php
} else {
    header("location:../index.php");
}
?>