<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

if (!can('pay', 'view')) {
    die('Access Denied');
}

/* ================= Filters ================= */
$f_search    = $_GET['search'] ?? '';
$f_date_from = $_GET['date_from'] ?? '';
$f_date_to   = $_GET['date_to'] ?? '';
$f_status    = $_GET['status'] ?? '';

$params = [];
$where  = [];

if ($f_search) {
    $where[] = "(a.name LIKE ? OR v.description LIKE ?)";
    $params[] = "%$f_search%";
    $params[] = "%$f_search%";
}
if ($f_date_from) { $where[] = "v.payment_date >= ?"; $params[] = $f_date_from; }
if ($f_date_to)   { $where[] = "v.payment_date <= ?"; $params[] = $f_date_to; }
if ($f_status)    { $where[] = "v.status = ?";         $params[] = $f_status; }

$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// Fetch Company Settings for Header
$conf = $pdo->query("SELECT * FROM company_settings LIMIT 1")->fetch();

$query = "
    SELECT v.*, u.full_name, u.username, a.name AS agent_name
    FROM payment_vouchers v
    LEFT JOIN users u ON v.user_id = u.user_id
    LEFT JOIN agents a ON v.ref_id = a.agent_id
    $where_sql
    ORDER BY v.payment_date DESC, v.payment_id DESC
";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$vouchers = $stmt->fetchAll();

// Calculation for Totals (Active Only)
$total_amount = 0;
foreach($vouchers as $v) {
    if (strtolower($v['status']) !== 'inactive') {
        $total_amount += $v['amount'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Payment Vouchers Report</title>
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
<style>
    body { background:#f8fafc; font-family: 'Segoe UI', Tahoma, sans-serif; font-size: 13px; }
    .table-container { background:#fff; border-radius:10px; border:1px solid #e2e8f0; overflow: hidden; }
    .badge-active { background:#10b981; color:#fff; padding: 5px 10px; border-radius: 4px; font-size: 11px; }
    .badge-inactive { background:#ef4444; color:#fff; padding: 5px 10px; border-radius: 4px; font-size: 11px; }
    .row-inactive { background:#fef2f2 !important; }
    .text-strike { text-decoration: line-through !important; color: #94a3b8 !important; font-style: italic; }
    
    /* Print Styles */
    @media print {
        @page { size: portrait; margin: 10mm; }
        .no-print { display: none !important; }
        body { background: #fff; padding: 0; }
        .table-container { border: none; }
        .table th { background-color: #f8fafc !important; -webkit-print-color-adjust: exact; }
        .row-inactive { background: #fef2f2 !important; -webkit-print-color-adjust: exact; }
    }
    
    .report-header { border-bottom: 2px solid #334155; margin-bottom: 20px; padding-bottom: 10px; }
    .btn-action { width:32px; height:32px; display:inline-flex; align-items:center; justify-content:center; border-radius:6px; border:1px solid #e2e8f0; background:#fff; text-decoration:none; }
</style>
</head>
<body>

<div class="container-fluid py-4 px-4">

    <div class="report-header d-flex justify-content-between align-items-center">
        <div class="text-start">
            <h5 class="fw-bold m-0"><?= htmlspecialchars($conf['company_name_en'] ?? 'Company Name') ?></h5>
            <small class="text-muted"><?= htmlspecialchars($conf['address_en'] ?? '') ?></small>
        </div>
        <div class="text-center">
            <h3 class="fw-bold text-danger m-0">PAYMENT VOUCHERS REPORT</h3>
            <p class="small text-muted mb-0">Total Records: <?= count($vouchers) ?></p>
        </div>
        <div class="text-end text-right" dir="rtl">
            <h5 class="fw-bold m-0"><?= htmlspecialchars($conf['company_name_ar'] ?? 'اسم الشركة') ?></h5>
            <small class="text-muted"><?= htmlspecialchars($conf['address_ar'] ?? '') ?></small>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div class="d-flex gap-2">
            <a href="dashboard.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left"></i></a>
            <button onclick="window.print()" class="btn btn-success btn-sm px-3">
                <i class="fas fa-print me-2"></i> Print Report
            </button>
        </div>
        <a href="pay_add.php" class="btn btn-danger btn-sm px-4"><i class="fas fa-plus me-2"></i> New Payment</a>
    </div>

    <div class="card mb-4 p-3 no-print">
        <form method="GET" class="row g-2">
            <div class="col-md-4">
                <label class="small fw-bold">Search</label>
                <input type="text" name="search" value="<?= htmlspecialchars($f_search) ?>" class="form-control form-control-sm" placeholder="Agent or description">
            </div>
            <div class="col-md-2">
                <label class="small fw-bold">From</label>
                <input type="date" name="date_from" value="<?= $f_date_from ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="small fw-bold">To</label>
                <input type="date" name="date_to" value="<?= $f_date_to ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="small fw-bold">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All</option>
                    <option value="active" <?= $f_status=='active'?'selected':'' ?>>Active</option>
                    <option value="inactive" <?= $f_status=='inactive'?'selected':'' ?>>Void</option>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end gap-1">
                <button class="btn btn-sm btn-dark flex-grow-1">Apply</button>
                <a href="pay.php" class="btn btn-sm btn-light border"><i class="fas fa-undo"></i></a>
            </div>
        </form>
    </div>

    <div class="table-container">
        <table class="table table-bordered align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th width="100">Date</th>
                    <th width="80">No.</th>
                    <th>Agent / Account</th>
                    <th>Description</th>
                    <th width="120">Amount</th>
                    <th width="100">Status</th>
                    <th width="130">User</th>
                    <th class="text-center no-print" width="100">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($vouchers as $v): 
                    $is_void = (strtolower($v['status']) === 'inactive');
                    $st_class = $is_void ? 'text-strike' : '';
                ?>
                <tr class="<?= $is_void ? 'row-inactive' : '' ?>">
                    <td><?= date('d/m/Y', strtotime($v['payment_date'])) ?></td>
                    <td class="fw-bold">#<?= $v['payment_no'] ?></td>
                    <td class="<?= $st_class ?>"><?= htmlspecialchars($v['agent_name'] ?? 'General Expense') ?></td>
                    <td class="<?= $st_class ?> small"><?= htmlspecialchars($v['description']) ?></td>
                    <td class="fw-bold <?= $is_void ? 'text-strike' : 'text-danger' ?>">
                        <?= number_format($v['amount'], 2) ?>
                    </td>
                    <td>
                        <span class="<?= $is_void ? 'badge-inactive' : 'badge-active' ?>">
                            <?= $is_void ? 'VOID' : 'ACTIVE' ?>
                        </span>
                    </td>
                    <td class="small">
                        <?= htmlspecialchars($v['full_name'] ?: $v['username']) ?>
                    </td>
                    <td class="text-center no-print">
                        <div class="d-flex justify-content-center gap-1">
                            <a href="pay_view.php?id=<?= $v['payment_id'] ?>" class="btn-action"><i class="fas fa-eye text-primary"></i></a>
                            <?php if(!$is_void): ?>
                            <a href="pay_delete.php?id=<?= $v['payment_id'] ?>" class="btn-action"><i class="fas fa-trash-alt text-danger"></i></a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="table-dark">
                    <td colspan="4" class="text-end fw-bold">TOTAL ACTIVE PAYMENTS:</td>
                    <td class="fw-bold"><?= number_format($total_amount, 2) ?></td>
                    <td colspan="4" class="small text-warning">Note: Voided vouchers are excluded from total.</td>
                </tr>
            </tfoot>
        </table>
    </div>

    <div class="mt-4 d-none d-print-block">
        <div class="row">
            <div class="col-4 text-center">
                <p class="fw-bold">Accountant</p>
                <br>----------
            </div>
            <div class="col-4 text-center">
                <p class="fw-bold">Manager</p>
                <br>----------
            </div>
            <div class="col-4 text-center">
                <p class="fw-bold">Date & Time</p>
                <small><?= date('Y-m-d H:i:s') ?></small>
            </div>
        </div>
    </div>

</div>

</body>
</html>