<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

$aid = $_SESSION['agency_id'];
$search = $_GET['search'] ?? '';

// 1. Calculate Totals for the Agency
$totals_billed = $conn->query("SELECT SUM(amount) as total FROM invoices WHERE agency_id = $aid")->fetch_assoc()['total'] ?? 0;
$totals_paid = $conn->query("SELECT SUM(amount_paid) as total FROM saas_payments WHERE agency_id = $aid")->fetch_assoc()['total'] ?? 0;
$current_balance = $conn->query("SELECT balance_due FROM agencies WHERE id = $aid")->fetch_assoc()['balance_due'] ?? 0;

// 2. Fetch Detailed Unified History
// We use NULL as placeholders to keep column counts same for UNION
$query = "(SELECT 'Bill' as type, id as ref_id, description, amount, status, created_at, 'N/A' as method FROM invoices WHERE agency_id = $aid)
          UNION 
          (SELECT 'Payment' as type, id as ref_id, notes as description, amount_paid as amount, 'Received' as status, created_at, payment_method as method FROM saas_payments WHERE agency_id = $aid)
          ORDER BY created_at DESC";

$history = $conn->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Subscription Ledger | Travel SaaS</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&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; --secondary: #1e293b; --bg: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg); padding: 40px; }
        .container { max-width: 1100px; margin: auto; }
        
        /* Top Navigation */
        .btn-back { text-decoration: none; color: #64748b; font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; margin-bottom: 20px; }
        .btn-back:hover { color: var(--primary); }

        /* Summary Cards */
        .summary-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; }
        .sum-card { background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); }
        .sum-card small { color: #94a3b8; text-transform: uppercase; font-size: 11px; font-weight: 700; letter-spacing: 1px; }
        .sum-card h2 { margin-top: 5px; font-size: 24px; color: var(--secondary); }

        /* Table Card */
        .card { background: white; padding: 30px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; border-bottom: 2px solid #edf2f7; }
        td { padding: 18px 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; vertical-align: middle; }
        
        /* Status Badges */
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .badge-bill { background: #fee2e2; color: #b91c1c; }
        .badge-pay { background: #dcfce7; color: #15803d; }
        .status-unpaid { color: var(--danger); }
        .status-paid { color: var(--success); font-weight: 600; }

        .btn-view { padding: 6px 12px; border-radius: 6px; background: #f1f5f9; color: var(--primary); text-decoration: none; font-size: 12px; font-weight: 600; border: 1px solid #e2e8f0; }
        .btn-view:hover { background: var(--primary); color: white; }
    </style>
</head>
<body>

<div class="container">
    <a href="dashboard.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
    
    <div style="display:flex; justify-content: space-between; align-items: flex-end; margin-bottom: 25px;">
        <div>
            <h1 style="font-size: 28px;">Subscription Ledger</h1>
            <p style="color: #64748b;">Financial history of your software usage.</p>
        </div>
        <div style="text-align:right;">
            <button onclick="window.print()" class="btn-view" style="background:var(--secondary); color:white; padding:10px 20px;"><i class="fas fa-print"></i> Print Statement</button>
        </div>
    </div>

    <div class="summary-grid">
        <div class="sum-card" style="border-left: 5px solid #cbd5e1;">
            <small>Total Billed</small>
            <h2>PKR <?php echo number_format($totals_billed); ?></h2>
        </div>
        <div class="sum-card" style="border-left: 5px solid var(--success);">
            <small>Total Paid</small>
            <h2 style="color: var(--success);">PKR <?php echo number_format($totals_paid); ?></h2>
        </div>
        <div class="sum-card" style="border-left: 5px solid <?php echo ($current_balance > 0 ? 'var(--danger)' : 'var(--success)'); ?>;">
            <small>Outstanding Balance</small>
            <h2 style="color: <?php echo ($current_balance > 0 ? 'var(--danger)' : 'var(--success)'); ?>;">
                PKR <?php echo number_format($current_balance); ?>
            </h2>
        </div>
    </div>

    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Ref ID</th>
                    <th>Transaction Details</th>
                    <th>Method</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $history->fetch_assoc()): 
                    $is_bill = ($row['type'] == 'Bill');
                ?>
                <tr>
                    <td>
                        <b><?php echo date('d M Y', strtotime($row['created_at'])); ?></b><br>
                        <small style="color: #94a3b8; font-size: 11px;"><?php echo date('h:i A', strtotime($row['created_at'])); ?></small>
                    </td>
                    <td>
                        <span class="badge <?php echo $is_bill ? 'badge-bill' : 'badge-pay'; ?>">
                            <?php echo $is_bill ? 'INV-'.$row['ref_id'] : 'PAY-'.$row['ref_id']; ?>
                        </span>
                    </td>
                    <td>
                        <strong style="display:block;"><?php echo $row['description']; ?></strong>
                        <small style="color: #64748b;"><?php echo $row['type']; ?> Issued</small>
                    </td>
                    <td>
                        <span style="font-size: 12px; color: #475569; font-weight: 500;">
                            <?php echo $row['method'] != 'N/A' ? '<i class="fas fa-university"></i> '.$row['method'] : '-'; ?>
                        </span>
                    </td>
                    <td>
                        <b style="font-size: 15px; color: <?php echo $is_bill ? 'var(--secondary)' : 'var(--success)'; ?>;">
                            PKR <?php echo number_format($row['amount']); ?>
                        </b>
                    </td>
                    <td class="<?php echo ($row['status'] == 'Paid' || $row['status'] == 'Received' ? 'status-paid' : 'status-unpaid'); ?>">
                        <i class="fas <?php echo ($row['status'] == 'Paid' || $row['status'] == 'Received' ? 'fa-check-circle' : 'fa-clock'); ?>"></i>
                        <?php echo $row['status']; ?>
                    </td>
                    <td>
                        <?php if($is_bill): ?>
                            <a href="view_invoice.php?id=<?php echo $row['ref_id']; ?>" class="btn-view" target="_blank">
                                <i class="fas fa-file-pdf"></i> View
                            </a>
                        <?php else: ?>
                            <span style="color:#cbd5e1; font-style:italic; font-size: 12px;">Paid</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php if($history->num_rows == 0) echo "<tr><td colspan='7' style='text-align:center; padding:50px; color:#94a3b8;'>No transactions found.</td></tr>"; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>