<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

// Check if staff is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$staffEmail = $_SESSION['email'];

// Get staff details
$staffQuery = "SELECT * FROM staff WHERE email = '$staffEmail'";
$staffResult = mysqli_query($conn, $staffQuery);

if (!$staffResult) {
    die("Database query failed: " . mysqli_error($conn));
}

$staffData = mysqli_fetch_assoc($staffResult);

// Handle form submission for adding new invoice
$successMessage = $errorMessage = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_invoice'])) {
        $student_type = mysqli_real_escape_string($conn, $_POST['student_type']);
        $description = mysqli_real_escape_string($conn, $_POST['description']);
        $amount = mysqli_real_escape_string($conn, $_POST['amount']);
        $year = mysqli_real_escape_string($conn, $_POST['year']);
        $semester = mysqli_real_escape_string($conn, $_POST['semester']);
        $due_date = mysqli_real_escape_string($conn, $_POST['due_date']);
        
        if (empty($student_type) || empty($description) || empty($amount) || empty($year) || empty($semester)) {
            $errorMessage = "Please fill in all required fields!";
        } else {
            $checkQuery = "SELECT * FROM association_invoice 
                          WHERE student_type = '$student_type' 
                          AND year = '$year' 
                          AND semester = '$semester' 
                          AND description = '$description'";
            $checkResult = mysqli_query($conn, $checkQuery);
            
            if (mysqli_num_rows($checkResult) > 0) {
                $errorMessage = "An invoice with the same details already exists!";
            } else {
                $insertQuery = "INSERT INTO association_invoice 
                               (student_type, description, amount, year, semester, due_date, created_at) 
                               VALUES 
                               ('$student_type', '$description', '$amount', '$year', '$semester', '$due_date', NOW())";
                
                if (mysqli_query($conn, $insertQuery)) {
                    $successMessage = "Invoice created successfully!";
                } else {
                    $errorMessage = "Error: " . mysqli_error($conn);
                }
            }
        }
    }
    
    if (isset($_POST['update_invoice'])) {
        $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
        $student_type = mysqli_real_escape_string($conn, $_POST['student_type']);
        $description = mysqli_real_escape_string($conn, $_POST['description']);
        $amount = mysqli_real_escape_string($conn, $_POST['amount']);
        $year = mysqli_real_escape_string($conn, $_POST['year']);
        $semester = mysqli_real_escape_string($conn, $_POST['semester']);
        $due_date = mysqli_real_escape_string($conn, $_POST['due_date']);
        
        $updateQuery = "UPDATE association_invoice 
                       SET student_type = '$student_type',
                           description = '$description',
                           amount = '$amount',
                           year = '$year',
                           semester = '$semester',
                           due_date = '$due_date'
                       WHERE id = '$invoice_id'";
        
        if (mysqli_query($conn, $updateQuery)) {
            $successMessage = "Invoice updated successfully!";
        } else {
            $errorMessage = "Error updating invoice: " . mysqli_error($conn);
        }
    }
    
    // Handle AJAX delete
    if (isset($_POST['delete_invoice'])) {
        $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
        
        $checkPayments = "SELECT COUNT(*) as payment_count FROM association_payment WHERE invoice_id = '$invoice_id'";
        $checkResult = mysqli_query($conn, $checkPayments);
        $paymentData = mysqli_fetch_assoc($checkResult);
        
        if ($paymentData['payment_count'] > 0) {
            echo json_encode(['success' => false, 'message' => 'Cannot delete invoice. There are payments associated with this invoice!']);
        } else {
            $deleteQuery = "DELETE FROM association_invoice WHERE id = '$invoice_id'";
            if (mysqli_query($conn, $deleteQuery)) {
                echo json_encode(['success' => true, 'message' => 'Invoice deleted successfully!']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error deleting invoice: ' . mysqli_error($conn)]);
            }
        }
        exit();
    }
    
    // Handle AJAX get invoice details
    if (isset($_POST['get_invoice_details'])) {
        $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
        
        $query = "SELECT * FROM association_invoice WHERE id = '$invoice_id'";
        $result = mysqli_query($conn, $query);
        $invoice = mysqli_fetch_assoc($result);
        
        if ($invoice) {
            $paymentQuery = "SELECT COUNT(*) as total_payments, 
                                    SUM(amount) as total_collected,
                                    COUNT(CASE WHEN status = 'Paid' THEN 1 END) as paid_count
                             FROM association_payment 
                             WHERE invoice_id = '$invoice_id'";
            $paymentResult = mysqli_query($conn, $paymentQuery);
            $paymentStats = mysqli_fetch_assoc($paymentResult);
            
            $totalPayments = $paymentStats['total_payments'] ?? 0;
            $totalCollected = $paymentStats['total_collected'] ?? 0;
            $paidCount = $paymentStats['paid_count'] ?? 0;
            
            $html = '
            <div class="row">
                <div class="col-md-6">
                    <h6>Invoice Information</h6>
                    <p><strong>Student Type:</strong> ' . htmlspecialchars($invoice['student_type']) . '</p>
                    <p><strong>Description:</strong> ' . htmlspecialchars($invoice['description']) . '</p>
                    <p><strong>Amount:</strong> <span class="text-primary fw-bold">K ' . number_format($invoice['amount'], 2) . '</span></p>
                </div>
                <div class="col-md-6">
                    <h6>Period & Dates</h6>
                    <p><strong>Year:</strong> ' . $invoice['year'] . '</p>
                    <p><strong>Semester:</strong> ' . $invoice['semester'] . '</p>
                    <p><strong>Due Date:</strong> ' . ($invoice['due_date'] ? date('d/m/Y', strtotime($invoice['due_date'])) : 'Not set') . '</p>
                    <p><strong>Created:</strong> ' . date('d/m/Y h:i A', strtotime($invoice['created_at'])) . '</p>
                </div>
            </div>
            
            <hr>
            
            <div class="row">
                <div class="col-md-12">
                    <h6>Payment Statistics</h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="text-center p-3 bg-light rounded">
                                <h3 class="text-primary">' . $totalPayments . '</h3>
                                <p class="mb-0">Total Payments</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3 bg-light rounded">
                                <h3 class="text-success">' . $paidCount . '</h3>
                                <p class="mb-0">Paid Students</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3 bg-light rounded">
                                <h3 class="text-info">K ' . number_format($totalCollected, 2) . '</h3>
                                <p class="mb-0">Total Collected</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>';
            
            echo $html;
        } else {
            echo '<div class="alert alert-danger">Invoice not found!</div>';
        }
        exit();
    }
}

// Fetch all invoices
$invoiceQuery = "SELECT * FROM association_invoice ORDER BY year DESC, semester DESC, student_type";
$invoiceResult = mysqli_query($conn, $invoiceQuery);

// Get current year for default
$currentYear = date('Y');

// Get statistics
$totalQuery = "SELECT COUNT(*) as total FROM association_invoice";
$totalResult = mysqli_query($conn, $totalQuery);
$totalData = mysqli_fetch_assoc($totalResult);

$currentQuery = "SELECT COUNT(*) as total FROM association_invoice WHERE year = '$currentYear'";
$currentResult = mysqli_query($conn, $currentQuery);
$currentData = mysqli_fetch_assoc($currentResult);

$amountQuery = "SELECT SUM(amount) as total FROM association_invoice";
$amountResult = mysqli_query($conn, $amountQuery);
$amountData = mysqli_fetch_assoc($amountResult);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Association Invoice Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
        }
        
        body {
            background: #f5f7fb;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-top: 70px;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border: none;
            margin-bottom: 20px;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .btn-primary {
            background: var(--primary-color);
            border: none;
        }
        
        .btn-primary:hover {
            background: var(--secondary-color);
        }
        
        .stats-card {
            text-align: center;
            padding: 20px;
            border-radius: 10px;
            color: white;
            margin-bottom: 20px;
        }
        
        .stats-card.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stats-card.active { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .stats-card.amount { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        
        .table-hover tbody tr:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }
        
        .action-buttons .btn {
            margin: 0 2px;
            padding: 4px 8px;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>

<?php include "../include/nav.php";?>

<div class="content mt-4">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0"><i class="fa fa-file-invoice me-2"></i>Association Invoice Management</h1>
            <p class="text-muted">Create and manage student association fee invoices</p>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="stats-card total">
                <i class="fa fa-file-alt fa-3x mb-3"></i>
                <h3><?php echo number_format($totalData['total'] ?? 0); ?></h3>
                <p>Total Invoices</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stats-card active">
                <i class="fa fa-calendar-check fa-3x mb-3"></i>
                <h3><?php echo number_format($currentData['total'] ?? 0); ?></h3>
                <p>Current Year Invoices</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stats-card amount">
                <i class="fa fa-money-bill-wave fa-3x mb-3"></i>
                <h3>K <?php echo number_format($amountData['total'] ?? 0, 2); ?></h3>
                <p>Total Invoice Amount</p>
            </div>
        </div>
    </div>

    <!-- Messages -->
    <?php if ($successMessage): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fa fa-check-circle me-2"></i> <?php echo $successMessage; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($errorMessage): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fa fa-exclamation-circle me-2"></i> <?php echo $errorMessage; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>

    <div class="row">
        <!-- Invoice Form -->
        <div class="col-lg-5">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-plus-circle me-2"></i>Create New Invoice</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Student Type *</label>
                                <input type="text" class="form-control" name="student_type" required
                                       placeholder="e.g., Undergraduate, Postgraduate">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Description *</label>
                                <input type="text" class="form-control" name="description" required
                                       placeholder="e.g., Annual Association Fee">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Amount (K) *</label>
                                <input type="number" class="form-control" name="amount" step="0.01" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Year *</label>
                                <input type="number" class="form-control" name="year" 
                                       value="<?php echo $currentYear; ?>" min="2020" max="2030" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Semester *</label>
                                <select class="form-control" name="semester" required>
                                    <option value="1">Semester 1</option>
                                    <option value="2">Semester 2</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Due Date</label>
                                <input type="date" class="form-control" name="due_date">
                            </div>
                        </div>

                        <div class="d-grid">
                            <button type="submit" name="add_invoice" class="btn btn-primary btn-lg">
                                <i class="fa fa-plus-circle me-2"></i> Create Invoice
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Invoices List -->
        <div class="col-lg-7">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fa fa-list me-2"></i>All Invoices</h5>
                    <div>
                        <button class="btn btn-sm btn-light" onclick="refreshInvoices()">
                            <i class="fa fa-refresh"></i> Refresh
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="invoicesTable">
                            <thead>
                                <tr>
                                    <th>Student Type</th>
                                    <th>Description</th>
                                    <th>Amount</th>
                                    <th>Year/Semester</th>
                                    <th>Due Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                while($invoice = mysqli_fetch_assoc($invoiceResult)): 
                                    $dueDate = strtotime($invoice['due_date']);
                                    $today = time();
                                    $isOverdue = $dueDate && $dueDate < $today;
                                ?>
                                <tr class="<?php echo $isOverdue ? 'table-warning' : ''; ?>">
                                    <td><?php echo htmlspecialchars($invoice['student_type']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['description']); ?></td>
                                    <td><strong>K <?php echo number_format($invoice['amount'], 2); ?></strong></td>
                                    <td>
                                        <span class="badge bg-info">
                                            <?php echo $invoice['year'] . ' - S' . $invoice['semester']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($invoice['due_date']): ?>
                                        <?php echo date('d/m/Y', strtotime($invoice['due_date'])); ?>
                                        <?php if ($isOverdue): ?>
                                        <br><small class="text-danger"><i class="fa fa-exclamation-triangle"></i> Overdue</small>
                                        <?php endif; ?>
                                        <?php else: ?>
                                        <span class="text-muted">Not set</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="action-buttons">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editInvoice(<?php echo $invoice['id']; ?>)"
                                                data-bs-toggle="tooltip" title="Edit">
                                            <i class="fa fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-success" 
                                                onclick="viewInvoiceDetails(<?php echo $invoice['id']; ?>)"
                                                data-bs-toggle="tooltip" title="View Details">
                                            <i class="fa fa-eye"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteInvoice(<?php echo $invoice['id']; ?>)"
                                                data-bs-toggle="tooltip" title="Delete">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Invoice Modal -->
<div class="modal fade" id="viewInvoiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-file-invoice me-2"></i>Invoice Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="invoiceDetails">
                <!-- Details loaded via AJAX -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Invoice Modal -->
<div class="modal fade" id="editInvoiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-edit me-2"></i>Edit Invoice</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="editInvoiceForm">
                <!-- Edit form loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<!-- JavaScript Libraries -->
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable
    $('#invoicesTable').DataTable({
        "pageLength": 10,
        "order": [[3, 'desc'], [0, 'asc']]
    });
    
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    });
    
    // Set minimum date for due date field
    var today = new Date().toISOString().split('T')[0];
    $('input[name="due_date"]').attr('min', today);
});

// View invoice details
function viewInvoiceDetails(invoiceId) {
    $.ajax({
        url: '',
        type: 'POST',
        data: { 
            get_invoice_details: true,
            invoice_id: invoiceId
        },
        success: function(response) {
            $('#invoiceDetails').html(response);
            $('#viewInvoiceModal').modal('show');
        },
        error: function() {
            alert('Error loading invoice details');
        }
    });
}

// Edit invoice
function editInvoice(invoiceId) {
    $.ajax({
        url: '',
        type: 'POST',
        data: { 
            get_invoice_details: true,
            invoice_id: invoiceId
        },
        success: function(response) {
            // Parse the response to get invoice data
            // This is a simplified approach - in real implementation, you'd get JSON
            $.ajax({
                url: '',
                type: 'POST',
                data: {
                    get_edit_form: true,
                    invoice_id: invoiceId
                },
                success: function(formHtml) {
                    $('#editInvoiceForm').html(formHtml);
                    $('#editInvoiceModal').modal('show');
                }
            });
        },
        error: function() {
            alert('Error loading invoice data');
        }
    });
}

// Delete invoice
function deleteInvoice(invoiceId) {
    if (confirm('Are you sure you want to delete this invoice?')) {
        $.ajax({
            url: '',
            type: 'POST',
            data: { 
                delete_invoice: true,
                invoice_id: invoiceId
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    location.reload();
                } else {
                    alert(response.message);
                }
            },
            error: function() {
                alert('Error deleting invoice');
            }
        });
    }
}

// Refresh invoices list
function refreshInvoices() {
    location.reload();
}
</script>

<?php
// Handle AJAX for edit form
if (isset($_POST['get_edit_form'])) {
    $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
    $query = "SELECT * FROM association_invoice WHERE id = '$invoice_id'";
    $result = mysqli_query($conn, $query);
    $invoice = mysqli_fetch_assoc($result);
    
    if ($invoice) {
        echo '
        <form method="POST" action="">
            <input type="hidden" name="invoice_id" value="' . $invoice['id'] . '">
            <div class="mb-3">
                <label class="form-label">Student Type *</label>
                <input type="text" class="form-control" name="student_type" 
                       value="' . htmlspecialchars($invoice['student_type']) . '" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Description *</label>
                <input type="text" class="form-control" name="description" 
                       value="' . htmlspecialchars($invoice['description']) . '" required>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Amount (K) *</label>
                    <input type="number" class="form-control" name="amount" 
                           value="' . $invoice['amount'] . '" step="0.01" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Year *</label>
                    <input type="number" class="form-control" name="year" 
                           value="' . $invoice['year'] . '" min="2020" max="2030" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Semester *</label>
                    <select class="form-control" name="semester" required>
                        <option value="1" ' . ($invoice['semester'] == '1' ? 'selected' : '') . '>Semester 1</option>
                        <option value="2" ' . ($invoice['semester'] == '2' ? 'selected' : '') . '>Semester 2</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Due Date</label>
                    <input type="date" class="form-control" name="due_date" 
                           value="' . $invoice['due_date'] . '">
                </div>
            </div>
            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="update_invoice" class="btn btn-primary">
                    <i class="fa fa-save me-1"></i> Update Invoice
                </button>
            </div>
        </form>';
    }
    exit();
}
?>
</body>
</html>