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

$agency_id = $_SESSION['agency_id'];
$client_id = (int)$_GET['id'];

// 1. Handle Date Filters
$from_date = $_GET['from_date'] ?? '';
$to_date = $_GET['to_date'] ?? '';

// 2. Base Query Condition
$where_clause = "WHERE client_id = $client_id AND agency_id = $agency_id";
if(!empty($from_date) && !empty($to_date)) {
    $where_clause .= " AND payment_date BETWEEN '$from_date' AND '$to_date'";
}

// 3. Fetch Client Info
$client = $conn->query("SELECT * FROM clients WHERE id = $client_id AND agency_id = $agency_id")->fetch_assoc();
if(!$client) die("Access Denied.");

// 4. Fetch Totals for the Selected Period
$totals = $conn->query("SELECT 
    SUM(CASE WHEN transaction_type = 'Debit' THEN amount ELSE 0 END) as total_debit,
    SUM(CASE WHEN transaction_type = 'Credit' THEN amount ELSE 0 END) as total_credit
    FROM payments $where_clause")->fetch_assoc();

$balance = ($totals['total_debit'] ?? 0) - ($totals['total_credit'] ?? 0);

// 5. Fetch Transaction History for the Selected Period
$history = $conn->query("SELECT * FROM payments $where_clause ORDER BY payment_date DESC, id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Account Statement | <?php echo $client['name']; ?></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; --secondary: #1e293b; --success: #1cc88a; --danger: #e74a3b; --bg-color: #f8f9fc; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg-color); padding: 40px; }
        .container { max-width: 1200px; margin: auto; }
        
        /* Header & Filter Bar */
        .header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 25px; }
        .filter-card { background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); margin-bottom: 25px; display: flex; align-items: center; gap: 15px; flex-wrap: wrap; }
        .filter-card input { padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-size: 13px; }
        
        /* Summary Cards */
        .summary-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; }
        .stat-box { padding: 25px; border-radius: 15px; color: white; position: relative; overflow: hidden; box-shadow: 0 10px 20px rgba(0,0,0,0.05); }
        .stat-box i { position: absolute; right: -10px; bottom: -10px; font-size: 80px; opacity: 0.15; }
        .stat-box small { text-transform: uppercase; font-size: 11px; font-weight: 600; letter-spacing: 1px; opacity: 0.9; }
        .stat-box h2 { font-size: 28px; margin-top: 5px; }

        /* Table Styling */
        .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; }
        th { text-align: left; padding: 15px; background: #f8f9fc; color: #64748b; font-size: 11px; text-transform: uppercase; border-bottom: 2px solid #eee; }
        td { padding: 15px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
        
        .btn { padding: 10px 20px; border-radius: 8px; text-decoration: none; font-size: 12px; font-weight: 600; color: white; border: none; cursor: pointer; transition: 0.3s; }
        .btn-filter { background: var(--secondary); }
        .btn-reset { background: #f1f5f9; color: #475569; }
        
        .debit-text { color: var(--danger); font-weight: 600; }
        .credit-text { color: var(--success); font-weight: 600; }

        @media print { .no-print { display: none; } body { background: #fff; padding: 0; } .card { box-shadow: none; border: 1px solid #eee; } }
    </style>
</head>
<body>

<div class="container">
    <!-- Action Header -->
    <div class="header">
        <div>
            <a href="ledger.php" class="no-print" style="text-decoration:none; color:var(--primary); font-weight:600;"><i class="fas fa-arrow-left"></i> Back to All Accounts</a>
            <h1 style="margin-top:10px;">Account Statement</h1>
            <p style="color: #64748b;"><b><?php echo $client['name']; ?></b> | <i class="fas fa-phone"></i> <?php echo $client['phone_number']; ?></p>
        </div>
        <div class="no-print" style="display:flex; gap:10px;">
            <button onclick="window.print()" class="btn" style="background:#2d3436;"><i class="fas fa-print"></i> Print</button>
            <a href="add_transaction.php?client_id=<?php echo $client_id; ?>" class="btn" style="background:var(--primary);"><i class="fas fa-plus"></i> New Entry</a>
        </div>
    </div>

    <!-- Period Filter Bar -->
    <form class="filter-card no-print" method="GET">
        <input type="hidden" name="id" value="<?php echo $client_id; ?>">
        <div style="display:flex; align-items:center; gap:10px;">
            <label style="font-size: 12px; font-weight: 600; color: #64748b;">FROM:</label>
            <input type="date" name="from_date" value="<?php echo $from_date; ?>">
        </div>
        <div style="display:flex; align-items:center; gap:10px;">
            <label style="font-size: 12px; font-weight: 600; color: #64748b;">TO:</label>
            <input type="date" name="to_date" value="<?php echo $to_date; ?>">
        </div>
        <button type="submit" class="btn btn-filter">Apply Filter</button>
        <?php if($from_date): ?><a href="view_client_ledger.php?id=<?php echo $client_id; ?>" class="btn btn-reset">Clear</a><?php endif; ?>
        
        <?php if($from_date): ?>
            <span style="font-size: 12px; color: var(--primary); font-weight: 600; margin-left: auto;">
                Showing: <?php echo date('d M Y', strtotime($from_date)); ?> to <?php echo date('d M Y', strtotime($to_date)); ?>
            </span>
        <?php endif; ?>
    </form>

    <!-- Summary Statistics -->
    <div class="summary-grid">
        <div class="stat-box" style="background: linear-gradient(135deg, #e74a3b 0%, #be281a 100%);">
            <small>Total Debit (+)</small>
            <h2>PKR <?php echo number_format($totals['total_debit'] ?? 0); ?></h2>
            <i class="fas fa-arrow-up"></i>
        </div>
        <div class="stat-box" style="background: linear-gradient(135deg, #1cc88a 0%, #169b6b 100%);">
            <small>Total Credit (-)</small>
            <h2>PKR <?php echo number_format($totals['total_credit'] ?? 0); ?></h2>
            <i class="fas fa-arrow-down"></i>
        </div>
        <div class="stat-box" style="background: linear-gradient(135deg, #2e3751 0%, #1e293b 100%);">
            <small>Net Statement Balance</small>
            <h2>PKR <?php echo number_format($balance); ?></h2>
            <i class="fas fa-wallet"></i>
        </div>
    </div>

    <!-- Transaction Table -->
    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Description / Details</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th class="no-print" style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $history->fetch_assoc()): ?>
                <tr>
                    <td style="font-weight: 600; color: #475569;"><?php echo date('d M, Y', strtotime($row['payment_date'])); ?></td>
                    <td><?php echo $row['notes']; ?></td>
                    <td>
                        <b class="<?php echo ($row['transaction_type'] == 'Debit' ? 'debit-text' : 'credit-text'); ?>">
                            <?php echo $row['transaction_type']; ?>
                        </b>
                    </td>
                    <td><b style="font-size: 15px;">PKR <?php echo number_format($row['amount']); ?></b></td>
                    <td class="no-print" style="text-align:right;">
                        <a href="edit_transaction.php?id=<?php echo $row['id']; ?>" style="color:var(--primary); margin-right:15px; font-size:16px;"><i class="fas fa-edit"></i></a>
                        <a href="handle_transaction.php?action=delete&id=<?php echo $row['id']; ?>&client_id=<?php echo $client_id; ?>" 
                           style="color:var(--danger); font-size:16px;" onclick="return confirm('Permanently delete this entry?')"><i class="fas fa-trash-alt"></i></a>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php if($history->num_rows == 0) echo "<tr><td colspan='5' style='text-align:center; padding:50px; color:#94a3b8;'><i class='fas fa-search' style='font-size:30px;'></i><br>No transactions found for the selected period.</td></tr>"; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>