<?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('receive','view')) {
    die('Access Denied');
}

/* ================= Filters ================= */
$f_customer  = $_GET['customer_id'] ?? '';
$f_date_from = $_GET['date_from'] ?? '';
$f_date_to   = $_GET['date_to'] ?? '';
$f_amt_min   = $_GET['amount_min'] ?? '';
$f_amt_max   = $_GET['amount_max'] ?? '';
$f_status    = $_GET['status'] ?? '';

$sort_by    = $_GET['sort_by'] ?? 'v.voucher_date';
$sort_order = ($_GET['sort_order'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';

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

if ($f_customer)  { $where[] = "v.customer_id = ?"; $params[] = $f_customer; }
if ($f_date_from) { $where[] = "v.voucher_date >= ?"; $params[] = $f_date_from; }
if ($f_date_to)   { $where[] = "v.voucher_date <= ?"; $params[] = $f_date_to; }
if ($f_amt_min)   { $where[] = "v.amount >= ?";       $params[] = $f_amt_min; }
if ($f_amt_max)   { $where[] = "v.amount <= ?";       $params[] = $f_amt_max; }
if ($f_status)    { $where[] = "v.status = ?";        $params[] = $f_status; }

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

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

$query = "
    SELECT v.*, c.name AS customer_name, u.full_name, u.username
    FROM receipt_vouchers v
    LEFT JOIN customers c ON v.customer_id = c.customer_id
    LEFT JOIN users u ON v.user_id = u.user_id
    $where_sql
    ORDER BY $sort_by $sort_order
";

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

$customers = $pdo->query("SELECT customer_id, name FROM customers ORDER BY name")->fetchAll();

// Calculation for Totals (Active Only)
$total_received = 0;
foreach($vouchers as $v) {
    if (strtolower($v['status']) !== 'inactive') {
        $total_received += $v['amount'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Receipt 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: 'Inter', 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; }
    
    @media print {
        .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; }
    }
    
    .report-header { border-bottom: 2px solid #0d6efd; 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-primary m-0 text-uppercase">Receipt Vouchers Report</h3>
            <p class="small text-muted mb-0">Filtered Results Summary</p>
        </div>
        <div class="text-end" 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 All
            </button>
        </div>
        <a href="receive_add.php" class="btn btn-primary btn-sm px-4"><i class="fas fa-plus me-2"></i> New Voucher</a>
    </div>

    <div class="card mb-4 p-3 no-print">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="fw-bold small">Customer</label>
                <select name="customer_id" class="form-select form-select-sm">
                    <option value="">All Customers</option>
                    <?php foreach($customers as $c): ?>
                        <option value="<?= $c['customer_id'] ?>" <?= $f_customer==$c['customer_id']?'selected':'' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="fw-bold small">From / To</label>
                <div class="input-group input-group-sm">
                    <input type="date" name="date_from" value="<?= $f_date_from ?>" class="form-control">
                    <input type="date" name="date_to" value="<?= $f_date_to ?>" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <label class="fw-bold small">Amount Range</label>
                <div class="input-group input-group-sm">
                    <input type="number" name="amount_min" value="<?= $f_amt_min ?>" class="form-control" placeholder="Min">
                    <input type="number" name="amount_max" value="<?= $f_amt_max ?>" class="form-control" placeholder="Max">
                </div>
            </div>
            <div class="col-md-2">
                <label class="fw-bold small">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All Status</option>
                    <option value="active" <?= $f_status=='active'?'selected':'' ?>>Active</option>
                    <option value="inactive" <?= $f_status=='inactive'?'selected':'' ?>>Inactive</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="receive.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 table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th width="100">Date</th>
                    <th>Customer Name</th>
                    <th width="150">Amount</th>
                    <th width="120">Status</th>
                    <th width="150">Created By</th>
                    <th class="text-center no-print" width="100">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($vouchers as $v):
                    $is_inactive = (strtolower($v['status']) === 'inactive');
                ?>
                <tr class="<?= $is_inactive ? 'row-inactive' : '' ?>">
                    <td><?= date('d/m/Y', strtotime($v['voucher_date'])) ?></td>
                    <td class="<?= $is_inactive ? 'text-strike' : 'fw-bold' ?>">
                        <?= htmlspecialchars($v['customer_name']) ?>
                    </td>
                    <td class="fw-bold <?= $is_inactive ? 'text-strike text-muted' : 'text-success' ?>">
                        <?= number_format($v['amount'], 2) ?>
                    </td>
                    <td>
                        <span class="badge <?= !$is_inactive ? 'badge-active' : 'badge-inactive' ?>">
                            <?= strtoupper($v['status']) ?>
                        </span>
                    </td>
                    <td>
                        <small class="text-muted"><i class="fas fa-user me-1"></i> <?= htmlspecialchars($v['full_name'] ?: $v['username']) ?></small>
                    </td>
                    <td class="text-center no-print">
                        <div class="d-flex justify-content-center gap-2">
                            <a href="receive_view.php?id=<?= $v['receipt_id'] ?>" class="btn-action" title="View"><i class="fas fa-eye text-primary"></i></a>
                            <?php if(!$is_inactive): ?>
                                <a href="receive_delete.php?id=<?= $v['receipt_id'] ?>" class="btn-action" title="Void"><i class="fas fa-rotate-left text-danger"></i></a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="table-primary">
                    <td colspan="2" class="text-end fw-bold text-uppercase">Total Active Receipts:</td>
                    <td class="fw-bold text-success fs-6" colspan="4">
                        <?= number_format($total_received, 2) ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>

    <div class="mt-5 d-none d-print-block">
        <div class="row text-center">
            <div class="col-4">
                <p class="fw-bold mb-4">Cashier</p>
                <div class="border-top mx-4"></div>
            </div>
            <div class="col-4">
                <p class="fw-bold mb-4">Accountant</p>
                <div class="border-top mx-4"></div>
            </div>
            <div class="col-4">
                <p class="fw-bold mb-4">Authorized Signature</p>
                <div class="border-top mx-4"></div>
            </div>
        </div>
        <div class="text-center mt-4">
            <small class="text-muted">Generated on: <?= date('d/m/Y H:i:s') ?></small>
        </div>
    </div>

</div>
</body>
</html>