<?php
$pageTitle = 'Laporan Pembayaran';
$activeMenu = 'reports';
require_once __DIR__ . '/../../includes/header.php';

$db = get_db_connection();
$clients = get_client_options();

$filters = [
    'start_date' => $_GET['start_date'] ?? date('Y-m-01'),
    'end_date' => $_GET['end_date'] ?? date('Y-m-t'),
    'status' => isset($_GET['status']) ? sanitize_input($_GET['status']) : '',
    'client_id' => isset($_GET['client_id']) ? (int) $_GET['client_id'] : 0,
];

$conditions = [];
$params = [];
$types = '';

if ($filters['start_date']) {
    $conditions[] = 'p.invoice_date >= ?';
    $types .= 's';
    $params[] = $filters['start_date'];
}
if ($filters['end_date']) {
    $conditions[] = 'p.invoice_date <= ?';
    $types .= 's';
    $params[] = $filters['end_date'];
}
if ($filters['status']) {
    $conditions[] = 'p.payment_status = ?';
    $types .= 's';
    $params[] = $filters['status'];
}
if ($filters['client_id'] > 0) {
    $conditions[] = 'p.client_id = ?';
    $types .= 'i';
    $params[] = $filters['client_id'];
}

$whereClause = '';
if (!empty($conditions)) {
    $whereClause = 'WHERE ' . implode(' AND ', $conditions);
}

$sql = 'SELECT p.*, c.full_name, c.client_code FROM payments p JOIN clients c ON c.id = p.client_id ' . $whereClause . ' ORDER BY p.invoice_date DESC';
$stmt = $db->prepare($sql);
if ($stmt && $types !== '') {
    $bindParams = [];
    $bindParams[] = &$types;
    foreach ($params as $key => $value) {
        $bindParams[] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], $bindParams);
}
if ($stmt) {
    $stmt->execute();
    $result = $stmt->get_result();
    $reports = $result->fetch_all(MYSQLI_ASSOC);
} else {
    $reports = [];
}

$summary = [
    'total_invoice' => 0,
    'total_paid' => 0.0,
    'total_pending' => 0.0,
    'total_overdue' => 0.0,
];

foreach ($reports as $row) {
    $amount = (float) $row['amount'];
    $summary['total_invoice'] += $amount;
    if ($row['payment_status'] === 'paid') {
        $summary['total_paid'] += $amount;
    }
    if ($row['payment_status'] === 'pending') {
        $summary['total_pending'] += $amount;
    }
    if ($row['payment_status'] === 'overdue') {
        $summary['total_overdue'] += $amount;
    }
}

$queryString = http_build_query(array_filter([
    'start_date' => $filters['start_date'],
    'end_date' => $filters['end_date'],
    'status' => $filters['status'] ?: null,
    'client_id' => $filters['client_id'] ?: null,
]));
$exportParams = $queryString ? ('?' . $queryString) : '';
?>
<div class="section-header d-flex flex-wrap justify-content-between align-items-center mb-4">
    <div>
    </div>
    <div class="section-actions mt-3 mt-lg-0">
        <a href="export_pdf.php<?php echo $exportParams; ?>" class="btn btn-outline-secondary">Export PDF</a>
        <a href="export_excel.php<?php echo $exportParams; ?>" class="btn btn-outline-success">Export Excel</a>
    </div>
</div>
<div class="card card-metric p-4 mb-4"> 
        <form class="row gy-3" method="GET">
        <div class="col-md-3">
            <label class="form-label">Tanggal Mulai</label>
            <input type="date" class="form-control" name="start_date" value="<?php echo htmlspecialchars($filters['start_date']); ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">Tanggal Selesai</label>
            <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($filters['end_date']); ?>">
        </div>
        <div class="col-md-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="">Semua Status</option>
                <option value="pending" <?php echo $filters['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="paid" <?php echo $filters['status'] === 'paid' ? 'selected' : ''; ?>>Paid</option>
                <option value="overdue" <?php echo $filters['status'] === 'overdue' ? 'selected' : ''; ?>>Overdue</option>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Pelanggan</label>
            <select name="client_id" class="form-select">
                <option value="0">Semua Pelanggan</option>
                <?php foreach ($clients as $client): ?>
                    <option value="<?php echo $client['id']; ?>" <?php echo (int) $filters['client_id'] === (int) $client['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($client['full_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-12 section-actions justify-content-end">
            <button type="submit" class="btn btn-primary">Terapkan</button>
            <a href="index.php" class="btn btn-outline-secondary">Reset</a>
        </div>
    </form>
</div>

<div class="row g-3 mb-4">
    <div class="col-12 col-md-6">
        <div class="card card-metric p-3">
            <p class="text-muted mb-1">Total Invoice</p>
            <h3 class="fw-bold mb-0"><?php echo format_currency($summary['total_invoice']); ?></h3>
        </div>
    </div>
    <div class="col-12 col-md-6">
        <div class="card card-metric p-3">
            <p class="text-muted mb-1">Total Paid</p>
            <h3 class="fw-bold mb-0 text-success"><?php echo format_currency($summary['total_paid']); ?></h3>
        </div>
    </div>
    <div class="col-12 col-md-6">
        <div class="card card-metric p-3">
            <p class="text-muted mb-1">Pending</p>
            <h3 class="fw-bold mb-0 text-warning"><?php echo format_currency($summary['total_pending']); ?></h3>
        </div>
    </div>
    <div class="col-12 col-md-6">
        <div class="card card-metric p-3">
            <p class="text-muted mb-1">Overdue</p>
            <h3 class="fw-bold mb-0 text-danger"><?php echo format_currency($summary['total_overdue']); ?></h3>
        </div>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-hover align-middle data-table">
        <thead>
            <tr>
                <th>Invoice</th>
                <th>Pelanggan</th>
                <th>Nominal</th>
                <th>Status</th>
                <th>Tgl Invoice</th>
                <th>Jatuh Tempo</th>
                <th>Tgl Bayar</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($reports)): ?>
                <tr>
                    <td colspan="7" class="text-center text-muted">Tidak ada data dengan filter saat ini.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($reports as $row): ?>
                    <tr>
                        <td class="fw-semibold"><?php echo htmlspecialchars($row['invoice_number']); ?></td>
                        <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                        <td><?php echo format_currency((float) $row['amount']); ?></td>
                        <td><span class="badge badge-status <?php echo status_badge_class($row['payment_status']); ?>"><?php echo ucfirst($row['payment_status']); ?></span></td>
                        <td><?php echo format_date($row['invoice_date']); ?></td>
                        <td><?php echo format_date($row['due_date']); ?></td>
                        <td><?php echo $row['payment_date'] ? format_date($row['payment_date']) : '-'; ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>











