<?php 
include 'config.php'; 
if(!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'SuperAdmin') {
    header("Location: dashboard.php"); exit();
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$agency_query = $conn->query("SELECT * FROM agencies WHERE id = $id");
if($agency_query->num_rows == 0) die("Agency not found.");
$agency = $agency_query->fetch_assoc();

// Updated Query: Pulling IDs so we can edit/delete specific rows
$history_sql = "(SELECT 'Invoice' as type, id, description, amount, created_at FROM invoices WHERE agency_id = $id)
                UNION 
                (SELECT 'Payment' as type, id, notes as description, amount_paid as amount, created_at FROM saas_payments WHERE agency_id = $id)
                ORDER BY created_at DESC";

$history = $conn->query($history_sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Agency Ledger Control</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #4e73df; --success: #1cc88a; --danger: #e74a3b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .card { background: #fff; padding: 30px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        .type-invoice { color: var(--danger); font-weight: 600; }
        .type-payment { color: var(--success); font-weight: 600; }
        .balance-box { background: #2e3751; color: white; padding: 25px; border-radius: 12px; margin-bottom: 25px; }
        .action-btn { padding: 5px 10px; border-radius: 6px; font-size: 12px; text-decoration: none; margin-left: 5px; transition: 0.3s; }
        .btn-edit { background: #f1f5f9; color: var(--primary); }
        .btn-del { background: #fff5f5; color: var(--danger); }
        .btn-edit:hover { background: var(--primary); color: white; }
        .btn-del:hover { background: var(--danger); color: white; }
    </style>
</head>
<body>

    <div style="margin-bottom: 30px;">
        <a href="saas_revenue.php" style="text-decoration:none; color:var(--primary); font-weight:600;"><i class="fas fa-arrow-left"></i> Back to Revenue</a>
        <h1 style="margin-top:10px;">Ledger Authority: <?php echo $agency['agency_name']; ?></h1>
    </div>

    <div class="balance-box">
        <small style="opacity: 0.7; text-transform: uppercase;">Current Outstanding Balance</small>
        <h2 style="font-size: 32px;">PKR <?php echo number_format($agency['balance_due']); ?></h2>
    </div>

    <div class="card">
        <h3>Transaction History</h3>
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Description</th>
                    <th>Amount</th>
                    <th style="text-align:right;">Authority Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $history->fetch_assoc()): 
                    $is_payment = ($row['type'] == 'Payment');
                ?>
                <tr>
                    <td><?php echo date('d M Y', strtotime($row['created_at'])); ?></td>
                    <td class="<?php echo ($is_payment ? 'type-payment' : 'type-invoice'); ?>">
                        <i class="fas <?php echo ($is_payment ? 'fa-check-circle' : 'fa-file-invoice-dollar'); ?>"></i>
                        <?php echo $row['type']; ?>
                    </td>
                    <td><?php echo $row['description']; ?></td>
                    <td><b>PKR <?php echo number_format($row['amount']); ?></b></td>
                    <td style="text-align:right;">
                        <?php if($is_payment): ?>
                            <!-- Edit and Delete for Payments -->
                            <a href="edit_saas_payment.php?id=<?php echo $row['id']; ?>" class="action-btn btn-edit"><i class="fas fa-edit"></i> Edit</a>
                            <a href="handle_saas_payment.php?delete=<?php echo $row['id']; ?>&amt=<?php echo $row['amount']; ?>&aid=<?php echo $id; ?>" 
                               class="action-btn btn-del" onclick="return confirm('WARNING: Deleting this payment will INCREASE the agency debt. Proceed?')"><i class="fas fa-trash"></i></a>
                        <?php else: ?>
                            <!-- View link for Invoices -->
                            <a href="view_invoice.php?id=<?php echo $row['id']; ?>" class="action-btn btn-edit" target="_blank"><i class="fas fa-eye"></i> View Inv</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

</body>
</html>