<?php
session_start();
require_once 'config.php';

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];

// ==================== HANDLE POST ACTIONS ====================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && isset($_POST['invoice_id'])) {
    $action = $_POST['action'];
    $invoice_id = intval($_POST['invoice_id']);
    
    if ($invoice_id > 0 && isset($conn) && $conn instanceof mysqli) {
        switch ($action) {
            case 'mark_paid':
                $payment_date = date('Y-m-d');
                $sql = "UPDATE invoices SET status = 'paid', payment_date = ? WHERE invoice_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("si", $payment_date, $invoice_id);
                    if ($stmt->execute() && $stmt->affected_rows > 0) {
                        $_SESSION['success_message'] = 'Invoice marked as paid successfully!';
                    } else {
                        $_SESSION['error_message'] = 'Invoice not found or already paid.';
                    }
                    $stmt->close();
                }
                break;
                
            case 'mark_sent':
                $sql = "UPDATE invoices SET status = 'sent' WHERE invoice_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $invoice_id);
                    if ($stmt->execute() && $stmt->affected_rows > 0) {
                        $_SESSION['success_message'] = 'Invoice marked as sent successfully!';
                    } else {
                        $_SESSION['error_message'] = 'Invoice not found.';
                    }
                    $stmt->close();
                }
                break;
                
            case 'cancel':
                $sql = "UPDATE invoices SET status = 'cancelled' WHERE invoice_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $invoice_id);
                    if ($stmt->execute() && $stmt->affected_rows > 0) {
                        $_SESSION['success_message'] = 'Invoice cancelled successfully!';
                    } else {
                        $_SESSION['error_message'] = 'Invoice not found.';
                    }
                    $stmt->close();
                }
                break;
                
            case 'delete':
                $sql = "DELETE FROM invoices WHERE invoice_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $invoice_id);
                    if ($stmt->execute() && $stmt->affected_rows > 0) {
                        $_SESSION['success_message'] = 'Invoice deleted successfully!';
                    } else {
                        $_SESSION['error_message'] = 'Invoice not found.';
                    }
                    $stmt->close();
                }
                break;
        }
    }
    
    if (isset($conn) && $conn->ping()) $conn->close();
    header('Location: super_admin_invoices.php');
    exit;
}

// ==================== HANDLE DOWNLOAD ACTION ====================
if (isset($_GET['action']) && $_GET['action'] === 'download' && isset($_GET['invoice_id'])) {
    $invoice_id = intval($_GET['invoice_id']);
    $invoice_data = null;
    
    if ($invoice_id > 0 && isset($conn) && $conn instanceof mysqli) {
        $sql = "SELECT i.*, s.school_name, s.email, s.phone, s.address, s.abbreviation 
                FROM invoices i 
                JOIN schools s ON i.school_id = s.school_id 
                WHERE i.invoice_id = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $invoice_id);
            if ($stmt->execute()) {
                $result = $stmt->get_result();
                if ($result->num_rows == 1) {
                    $invoice_data = $result->fetch_assoc();
                }
            }
            $stmt->close();
        }
    }
    
    if (!$invoice_data) die("Invoice not found!");
    
    // Generate HTML for download
    $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .header { display: table; width: 100%; margin-bottom: 30px; border-bottom: 3px solid #4f46e5; padding-bottom: 20px; }
        .header-left { display: table-cell; width: 50%; }
        .header-right { display: table-cell; width: 50%; text-align: right; }
        h1 { color: #4f46e5; margin: 0; font-size: 2em; }
        h2 { margin: 0; }
        .billing-info { display: table; width: 100%; margin: 30px 0; }
        .bill-to { display: table-cell; width: 50%; padding-right: 20px; }
        .invoice-details { display: table-cell; width: 50%; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th { background-color: #f8f9fa; padding: 12px; text-align: left; border-bottom: 2px solid #ddd; }
        td { padding: 12px; border-bottom: 1px solid #eee; }
        .totals { float: right; width: 300px; margin: 20px 0; }
        .totals-row { display: table; width: 100%; padding: 8px 0; border-bottom: 1px solid #eee; }
        .totals-label { display: table-cell; }
        .totals-value { display: table-cell; text-align: right; }
        .total-final { font-size: 1.3em; font-weight: bold; color: #4f46e5; border-top: 2px solid #4f46e5; padding-top: 10px; }
        .status-badge { display: inline-block; padding: 5px 15px; border-radius: 15px; font-weight: bold; }
        .notes { margin: 30px 0; padding: 15px; background-color: #f8f9fa; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <h1>DIVINE REPORTS</h1>
            <p>System Administration</p>
            <p>Email: admin@divinereports.com</p>
        </div>
        <div class="header-right">
            <h2>INVOICE</h2>
            <p><strong>' . htmlspecialchars($invoice_data['invoice_number']) . '</strong></p>
            <p>Date: ' . date('F d, Y', strtotime($invoice_data['invoice_date'])) . '</p>
            <p>Due: ' . date('F d, Y', strtotime($invoice_data['due_date'])) . '</p>
        </div>
    </div>
    <div class="billing-info">
        <div class="bill-to">
            <h3>Bill To:</h3>
            <p><strong>' . htmlspecialchars($invoice_data['school_name']) . '</strong></p>
            <p>' . htmlspecialchars($invoice_data['address'] ?? 'N/A') . '</p>
            <p>Email: ' . htmlspecialchars($invoice_data['email']) . '</p>
            <p>Phone: ' . htmlspecialchars($invoice_data['phone']) . '</p>
        </div>
        <div class="invoice-details">
            <h3>Invoice Details:</h3>
            <p><strong>Invoice #:</strong> ' . htmlspecialchars($invoice_data['invoice_number']) . '</p>
            <p><strong>School Code:</strong> ' . htmlspecialchars($invoice_data['abbreviation']) . '</p>
            <p><strong>Invoice Date:</strong> ' . date('M d, Y', strtotime($invoice_data['invoice_date'])) . '</p>
            <p><strong>Due Date:</strong> ' . date('M d, Y', strtotime($invoice_data['due_date'])) . '</p>';
    
    if ($invoice_data['payment_date']) {
        $html .= '<p><strong>Paid On:</strong> ' . date('M d, Y', strtotime($invoice_data['payment_date'])) . '</p>';
    }
    
    $html .= '</div>
    </div>
    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th style="text-align: right;">Amount</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><strong>School Management System Subscription</strong><br><small>Annual subscription for Divine Reports platform</small></td>
                <td style="text-align: right;">' . $invoice_data['currency'] . ' ' . number_format($invoice_data['amount'], 2) . '</td>
            </tr>
        </tbody>
    </table>
    <div class="totals">
        <div class="totals-row">
            <div class="totals-label">Subtotal:</div>
            <div class="totals-value">' . $invoice_data['currency'] . ' ' . number_format($invoice_data['amount'], 2) . '</div>
        </div>
        <div class="totals-row">
            <div class="totals-label">Tax:</div>
            <div class="totals-value">' . $invoice_data['currency'] . ' ' . number_format($invoice_data['tax_amount'], 2) . '</div>
        </div>
        <div class="totals-row total-final">
            <div class="totals-label">TOTAL:</div>
            <div class="totals-value">' . $invoice_data['currency'] . ' ' . number_format($invoice_data['total_amount'], 2) . '</div>
        </div>
    </div>
    <div style="clear: both;"></div>';
    
    if (!empty($invoice_data['notes'])) {
        $html .= '<div class="notes"><h3>Notes:</h3><p>' . nl2br(htmlspecialchars($invoice_data['notes'])) . '</p></div>';
    }
    
    $html .= '<div style="margin-top: 50px; text-align: center; color: #999; font-size: 0.9em;">
        <p>Thank you for your business!</p>
        <p>This is a computer-generated invoice. No signature required.</p>
    </div>
</body>
</html>';
    
    if (isset($conn) && $conn->ping()) $conn->close();
    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="Invoice_' . $invoice_data['invoice_number'] . '.html"');
    echo $html;
    exit;
}

// ==================== HANDLE VIEW ACTION ====================
if (isset($_GET['action']) && $_GET['action'] === 'view' && isset($_GET['invoice_id'])) {
    $invoice_id = intval($_GET['invoice_id']);
    $invoice_data = null;
    
    if ($invoice_id > 0 && isset($conn) && $conn instanceof mysqli) {
        $sql = "SELECT i.*, s.school_name, s.email, s.phone, s.address, s.abbreviation 
                FROM invoices i 
                JOIN schools s ON i.school_id = s.school_id 
                WHERE i.invoice_id = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $invoice_id);
            if ($stmt->execute()) {
                $result = $stmt->get_result();
                if ($result->num_rows == 1) {
                    $invoice_data = $result->fetch_assoc();
                }
            }
            $stmt->close();
        }
    }
    
    if (!$invoice_data) die("Invoice not found!");
    
    // Display invoice view
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Invoice <?php echo htmlspecialchars($invoice_data['invoice_number']); ?></title>
        <link rel="icon" href="images/logo.png" type="image/png">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
        <style>
            body { background: #f3f4f6; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; }
            .invoice-container { max-width: 900px; margin: 30px auto; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
            .invoice-header { display: flex; justify-content: space-between; margin-bottom: 40px; padding-bottom: 20px; border-bottom: 3px solid #4f46e5; }
            .company-info h1 { color: #4f46e5; margin: 0; font-size: 2em; }
            .company-info p { margin: 5px 0; color: #666; }
            .invoice-meta { text-align: right; }
            .invoice-meta h2 { color: #333; margin: 0; }
            .invoice-meta p { margin: 5px 0; color: #666; }
            .status-badge { display: inline-block; padding: 6px 16px; border-radius: 20px; font-weight: 600; margin-top: 10px; }
            .status-sent { background-color: #dbeafe; color: #1e40af; }
            .status-paid { background-color: #d1fae5; color: #065f46; }
            .status-overdue { background-color: #fee2e2; color: #991b1b; }
            .status-draft { background-color: #f3f4f6; color: #4b5563; }
            .status-cancelled { background-color: #fef3c7; color: #92400e; }
            .billing-info { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 40px; }
            .billing-section h3 { color: #333; margin-bottom: 15px; }
            .billing-section p { margin: 5px 0; color: #666; }
            .invoice-table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
            .invoice-table th { background-color: #f8f9fa; padding: 15px; text-align: left; font-weight: 600; border-bottom: 2px solid #e5e7eb; }
            .invoice-table td { padding: 15px; border-bottom: 1px solid #e5e7eb; color: #666; }
            .totals-section { float: right; width: 300px; margin-bottom: 40px; }
            .totals-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #e5e7eb; }
            .totals-row.total { font-size: 1.3em; font-weight: 700; color: #4f46e5; border-top: 2px solid #4f46e5; margin-top: 10px; }
            .notes-section { clear: both; margin-top: 40px; padding: 20px; background-color: #f8f9fa; border-radius: 8px; }
            .action-buttons { margin-top: 30px; text-align: center; padding-top: 30px; border-top: 2px solid #e5e7eb; }
            .btn { padding: 12px 30px; margin: 0 10px; border: none; border-radius: 8px; font-size: 1em; font-weight: 600; cursor: pointer; text-decoration: none; display: inline-block; }
            .btn-primary { background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; }
            .btn-secondary { background: #6b7280; color: white; }
            .btn-print { background: #10b981; color: white; }
            @media print { .action-buttons { display: none; } body { background: white; } .invoice-container { box-shadow: none; margin: 0; } }
        </style>
    </head>
    <body>
        <div class="invoice-container">
            <div class="invoice-header">
                <div class="company-info">
                    <h1><i class="fas fa-file-invoice"></i> DIVINE REPORTS</h1>
                    <p><strong>System Administration</strong></p>
                    <p>Email: admin@divinereports.com</p>
                </div>
                <div class="invoice-meta">
                    <h2>INVOICE</h2>
                    <p><strong><?php echo htmlspecialchars($invoice_data['invoice_number']); ?></strong></p>
                    <p>Date: <?php echo date('F d, Y', strtotime($invoice_data['invoice_date'])); ?></p>
                    <p>Due: <?php echo date('F d, Y', strtotime($invoice_data['due_date'])); ?></p>
                    <span class="status-badge status-<?php echo strtolower($invoice_data['status']); ?>">
                        <?php echo strtoupper($invoice_data['status']); ?>
                    </span>
                </div>
            </div>
            <div class="billing-info">
                <div class="billing-section">
                    <h3>Bill To:</h3>
                    <p><strong><?php echo htmlspecialchars($invoice_data['school_name']); ?></strong></p>
                    <p><?php echo htmlspecialchars($invoice_data['address'] ?? 'N/A'); ?></p>
                    <p>Email: <?php echo htmlspecialchars($invoice_data['email']); ?></p>
                    <p>Phone: <?php echo htmlspecialchars($invoice_data['phone']); ?></p>
                </div>
                <div class="billing-section">
                    <h3>Invoice Details:</h3>
                    <p><strong>Invoice #:</strong> <?php echo htmlspecialchars($invoice_data['invoice_number']); ?></p>
                    <p><strong>School Code:</strong> <?php echo htmlspecialchars($invoice_data['abbreviation']); ?></p>
                    <p><strong>Invoice Date:</strong> <?php echo date('M d, Y', strtotime($invoice_data['invoice_date'])); ?></p>
                    <p><strong>Due Date:</strong> <?php echo date('M d, Y', strtotime($invoice_data['due_date'])); ?></p>
                    <?php if ($invoice_data['payment_date']): ?>
                    <p><strong>Paid On:</strong> <?php echo date('M d, Y', strtotime($invoice_data['payment_date'])); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <table class="invoice-table">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th style="text-align: right;">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>School Management System Subscription</strong><br><small style="color: #999;">Annual subscription for Divine Reports platform</small></td>
                        <td style="text-align: right;"><?php echo $invoice_data['currency']; ?> <?php echo number_format($invoice_data['amount'], 2); ?></td>
                    </tr>
                </tbody>
            </table>
            <div class="totals-section">
                <div class="totals-row">
                    <span>Subtotal:</span>
                    <span><?php echo $invoice_data['currency']; ?> <?php echo number_format($invoice_data['amount'], 2); ?></span>
                </div>
                <div class="totals-row">
                    <span>Tax:</span>
                    <span><?php echo $invoice_data['currency']; ?> <?php echo number_format($invoice_data['tax_amount'], 2); ?></span>
                </div>
                <div class="totals-row total">
                    <span>TOTAL:</span>
                    <span><?php echo $invoice_data['currency']; ?> <?php echo number_format($invoice_data['total_amount'], 2); ?></span>
                </div>
            </div>
            <?php if (!empty($invoice_data['notes'])): ?>
            <div class="notes-section">
                <h3>Notes:</h3>
                <p><?php echo nl2br(htmlspecialchars($invoice_data['notes'])); ?></p>
            </div>
            <?php endif; ?>
            <div class="action-buttons">
                <button onclick="window.print()" class="btn btn-print"><i class="fas fa-print"></i> Print Invoice</button>
                <a href="?action=download&invoice_id=<?php echo $invoice_id; ?>" class="btn btn-primary"><i class="fas fa-download"></i> Download</a>
                <a href="super_admin_invoices.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
            </div>
        </div>
    </body>
    </html>
    <?php
    if (isset($conn) && $conn->ping()) $conn->close();
    exit;
}

// ==================== DEFAULT: INVOICE LIST PAGE ====================
$error_message = "";
$success_message = "";

// Check for session messages
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

// Fetch schools for invoice generation
$schools_list = [];
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT school_id, school_name, email, phone FROM schools ORDER BY school_name";
    if ($result = $conn->query($sql)) {
        while ($row = $result->fetch_assoc()) {
            $schools_list[] = $row;
        }
        $result->free();
    }
}

// Handle invoice generation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_invoice'])) {
    $school_id = intval($_POST['school_id']);
    $invoice_date = $_POST['invoice_date'];
    $due_date = $_POST['due_date'];
    $amount = floatval($_POST['amount']);
    $tax_amount = floatval($_POST['tax_amount'] ?? 0);
    $total_amount = $amount + $tax_amount;
    $notes = trim($_POST['notes']);
    
    $invoice_number = 'INV-' . date('Y') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    if (isset($conn) && $conn instanceof mysqli) {
        $sql = "INSERT INTO invoices (invoice_number, school_id, invoice_date, due_date, amount, tax_amount, total_amount, status, notes, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 'sent', ?, ?)";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("ssssdddsi", $invoice_number, $school_id, $invoice_date, $due_date, $amount, $tax_amount, $total_amount, $notes, $user_id);
            if ($stmt->execute()) {
                $success_message = "Invoice $invoice_number generated successfully!";
                
                // Send notification to school admin
                $message_subject = "New Invoice: $invoice_number";
                $message_content = "A new invoice has been generated.\n\nInvoice: $invoice_number\nAmount: UGX " . number_format($total_amount) . "\nDue: $due_date";
                
                $sql_admins = "SELECT id FROM users WHERE school_id = ? AND role = 1";
                if ($stmt_admins = $conn->prepare($sql_admins)) {
                    $stmt_admins->bind_param("i", $school_id);
                    $stmt_admins->execute();
                    $result_admins = $stmt_admins->get_result();
                    
                    while ($admin = $result_admins->fetch_assoc()) {
                        $sql_msg = "INSERT INTO messages (school_id, sender_id, receiver_id, subject, message_content, status) 
                                    VALUES (?, ?, ?, ?, ?, 'Unread')";
                        if ($stmt_msg = $conn->prepare($sql_msg)) {
                            $stmt_msg->bind_param("iiiss", $school_id, $user_id, $admin['id'], $message_subject, $message_content);
                            $stmt_msg->execute();
                            $stmt_msg->close();
                        }
                    }
                    $stmt_admins->close();
                }
            } else {
                $error_message = "Error generating invoice: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// Fetch all invoices
$invoices_list = [];
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT i.*, s.school_name FROM invoices i 
            JOIN schools s ON i.school_id = s.school_id 
            ORDER BY i.created_at DESC";
    if ($result = $conn->query($sql)) {
        while ($row = $result->fetch_assoc()) {
            $invoices_list[] = $row;
        }
        $result->free();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Management - Super Admin</title>
    <link rel="stylesheet" href="super_admin_layout.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Fixed Layout Styles */
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            margin-left: 250px; /* Adjust based on your sidebar width */
        }

        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
        }

        .invoices-container { max-width: 1200px; margin: 40px auto; padding: 0 20px; }
        .invoice-form-card { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.1); margin-bottom: 30px; }
        .invoice-form-card h3 { color: #333; margin-bottom: 20px; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group.full-width { grid-column: 1 / -1; }
        .form-group label { margin-bottom: 8px; font-weight: 600; color: #555; }
        .form-group input, .form-group select, .form-group textarea { padding: 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
        .btn-generate { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 12px 30px; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; }
        .invoices-table-card { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.1); }
        .invoices-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .invoices-table th, .invoices-table td { border: 1px solid #eee; padding: 12px; text-align: left; }
        .invoices-table th { background-color: #f8f9fa; font-weight: 600; color: #555; }
        .status-badge { padding: 4px 12px; border-radius: 12px; font-size: 0.85em; font-weight: 600; }
        .status-sent { background-color: #dbeafe; color: #1e40af; }
        .status-paid { background-color: #d1fae5; color: #065f46; }
        .status-overdue { background-color: #fee2e2; color: #991b1b; }
        .status-draft { background-color: #f3f4f6; color: #4b5563; }
        .status-cancelled { background-color: #fef3c7; color: #92400e; }
        .btn { padding: 6px 12px; margin: 2px; border: none; border-radius: 4px; font-size: 0.85em; cursor: pointer; transition: all 0.3s; text-decoration: none; display: inline-block; }
        .btn i { font-size: 0.9em; }
        .btn-info { background-color: #3b82f6; color: white; }
        .btn-info:hover { background-color: #2563eb; }
        .btn-primary { background-color: #8b5cf6; color: white; }
        .btn-primary:hover { background-color: #7c3aed; }
        .btn-success { background-color: #10b981; color: white; }
        .btn-success:hover { background-color: #059669; }
        .btn-warning { background-color: #f59e0b; color: white; }
        .btn-warning:hover { background-color: #d97706; }
        .btn-danger { background-color: #ef4444; color: white; }
        .btn-danger:hover { background-color: #dc2626; }
        .actions-cell { white-space: nowrap; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; transition: opacity 0.5s ease-out, transform 0.5s ease-out; }
        .alert-success { background-color: #d1fae5; color: #065f46; border: 1px solid #10b981; }
        .alert-error { background-color: #fee2e2; color: #991b1b; border: 1px solid #ef4444; }
        .alert.fade-out { opacity: 0; transform: translateY(-10px); }
        
        /* Confirmation Modal Styles */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); }
        .modal.active { display: flex; align-items: center; justify-content: center; }
        .modal-content { background-color: #fff; margin: auto; padding: 0; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.3); max-width: 450px; width: 90%; }
        .modal-header { padding: 20px 25px; border-bottom: 1px solid #e5e7eb; }
        .modal-header h3 { margin: 0; color: #333; font-size: 1.2em; }
        .modal-body { padding: 25px; color: #666; line-height: 1.6; }
        .modal-footer { padding: 15px 25px; border-top: 1px solid #e5e7eb; text-align: right; }
        .modal-footer button { margin-left: 10px; padding: 10px 20px; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; }
        .modal-footer .btn-confirm { background-color: #ef4444; color: white; }
        .modal-footer .btn-confirm.success { background-color: #10b981; }
        .modal-footer .btn-confirm.warning { background-color: #f59e0b; }
        .modal-footer .btn-cancel { background-color: #e5e7eb; color: #666; }
        
        @media (max-width: 768px) { .form-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            <div class="dashboard-content">
                <div class="invoices-container">
                    <h2><i class="fas fa-file-invoice-dollar"></i> Invoice Management</h2>
                    <?php if ($error_message): ?>
                        <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?></div>
                    <?php endif; ?>
                    <?php if ($success_message): ?>
                        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?></div>
                    <?php endif; ?>
                    <div class="invoice-form-card">
                        <h3>Generate New Invoice</h3>
                        <form method="POST" action="">
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Select School *</label>
                                    <select name="school_id" required>
                                        <option value="">-- Select School --</option>
                                        <?php foreach ($schools_list as $school): ?>
                                            <option value="<?php echo $school['school_id']; ?>"><?php echo htmlspecialchars($school['school_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Invoice Date *</label>
                                    <input type="date" name="invoice_date" value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Due Date *</label>
                                    <input type="date" name="due_date" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>Amount (UGX) *</label>
                                    <input type="number" name="amount" step="0.01" placeholder="5000000" required>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Tax Amount (UGX)</label>
                                    <input type="number" name="tax_amount" step="0.01" placeholder="0" value="0">
                                </div>
                            </div>
                            <div class="form-group full-width">
                                <label>Notes/Description</label>
                                <textarea name="notes" rows="4" placeholder="Enter invoice description or payment instructions..."></textarea>
                            </div>
                            <button type="submit" name="generate_invoice" class="btn-generate"><i class="fas fa-file-invoice"></i> Generate Invoice</button>
                        </form>
                    </div>
                    <div class="invoices-table-card">
                        <h3>All Invoices</h3>
                        <div style="overflow-x: auto;">
                            <table class="invoices-table">
                                <thead>
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>School</th>
                                        <th>Invoice Date</th>
                                        <th>Due Date</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($invoices_list)): ?>
                                        <tr><td colspan="7" style="text-align: center; padding: 30px; color: #999;">No invoices generated yet.</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($invoices_list as $invoice): ?>
                                            <tr>
                                                <td><strong><?php echo htmlspecialchars($invoice['invoice_number']); ?></strong></td>
                                                <td><?php echo htmlspecialchars($invoice['school_name']); ?></td>
                                                <td><?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></td>
                                                <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                <td>UGX <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                <td><span class="status-badge status-<?php echo strtolower($invoice['status']); ?>"><?php echo ucfirst($invoice['status']); ?></span></td>
                                                <td class="actions-cell">
                                                    <a href="?action=view&invoice_id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-info" target="_blank" title="View"><i class="fas fa-eye"></i></a>
                                                    <a href="?action=download&invoice_id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-primary" title="Download"><i class="fas fa-download"></i></a>
                                                    <?php if ($invoice['status'] === 'draft'): ?>
                                                    <button class="btn btn-warning" onclick="showConfirmModal(<?php echo $invoice['invoice_id']; ?>, 'mark_sent', 'Mark as Sent', 'Are you sure you want to mark this invoice as SENT?', 'warning')" title="Mark as Sent"><i class="fas fa-paper-plane"></i></button>
                                                    <?php endif; ?>
                                                    <?php if ($invoice['status'] === 'sent' || $invoice['status'] === 'overdue'): ?>
                                                    <button class="btn btn-success" onclick="showConfirmModal(<?php echo $invoice['invoice_id']; ?>, 'mark_paid', 'Mark as Paid', 'Are you sure you want to mark this invoice as PAID?', 'success')" title="Mark as Paid"><i class="fas fa-check-circle"></i></button>
                                                    <?php endif; ?>
                                                    <?php if ($invoice['status'] !== 'paid' && $invoice['status'] !== 'cancelled'): ?>
                                                    <button class="btn btn-warning" onclick="showConfirmModal(<?php echo $invoice['invoice_id']; ?>, 'cancel', 'Cancel Invoice', 'Are you sure you want to CANCEL this invoice?', 'warning')" title="Cancel"><i class="fas fa-ban"></i></button>
                                                    <?php endif; ?>
                                                    <button class="btn btn-danger" onclick="showConfirmModal(<?php echo $invoice['invoice_id']; ?>, 'delete', 'Delete Invoice', 'Are you sure you want to DELETE this invoice permanently? This action cannot be undone.', 'danger')" title="Delete"><i class="fas fa-trash"></i></button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>
    
    <!-- Confirmation Modal -->
    <div id="confirmModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Confirm Action</h3>
            </div>
            <div class="modal-body">
                <p id="modalMessage">Are you sure you want to proceed?</p>
            </div>
            <div class="modal-footer">
                <button class="btn-cancel" onclick="closeConfirmModal()">Cancel</button>
                <form method="POST" action="" style="display: inline;" id="confirmForm">
                    <input type="hidden" name="invoice_id" id="modalInvoiceId">
                    <input type="hidden" name="action" id="modalAction">
                    <button type="submit" class="btn-confirm" id="confirmButton">Confirm</button>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        const modal = document.getElementById('confirmModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalMessage = document.getElementById('modalMessage');
        const modalInvoiceId = document.getElementById('modalInvoiceId');
        const modalAction = document.getElementById('modalAction');
        const confirmButton = document.getElementById('confirmButton');
        
        function showConfirmModal(invoiceId, action, title, message, type) {
            modalTitle.textContent = title;
            modalMessage.textContent = message;
            modalInvoiceId.value = invoiceId;
            modalAction.value = action;
            
            // Reset button classes
            confirmButton.className = 'btn-confirm';
            if (type === 'success') {
                confirmButton.classList.add('success');
            } else if (type === 'warning') {
                confirmButton.classList.add('warning');
            }
            
            modal.classList.add('active');
        }
        
        function closeConfirmModal() {
            modal.classList.remove('active');
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target === modal) {
                closeConfirmModal();
            }
        }
        
        // Auto-hide alerts after 3 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    alert.classList.add('fade-out');
                    setTimeout(function() {
                        alert.remove();
                    }, 500); // Wait for fade animation to complete
                }, 3000); // 3 seconds
            });
        });
        
        // Sidebar toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>