<?php
session_start();
if (!isset($_SESSION['logged_in'])) { die('Access Denied'); }

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

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

/* ================= جلب الإعدادات (الهيدر) ================= */
$conf = $pdo->query("SELECT * FROM company_settings LIMIT 1")->fetch();

/* ================= محرك البحث والفلترة (نفس المنطق) ================= */
$f_search = trim($_GET['f_search'] ?? ''); 
$f_box    = $_GET['cashbox_id'] ?? '';
$f_date_f = $_GET['date_from'] ?? '';
$f_date_t = $_GET['date_to'] ?? '';
$f_status = $_GET['status'] ?? '';

$params = [];
$where  = ["1=1"];

if ($f_search !== '') {
    $where[] = "(ex.expense_name LIKE ? OR et.description LIKE ?)";
    $params[] = "%$f_search%"; $params[] = "%$f_search%";
}
if ($f_box !== '') { $where[] = "et.box_id = ?"; $params[] = $f_box; }
if ($f_date_f !== '') { $where[] = "et.trans_date >= ?"; $params[] = $f_date_f; }
if ($f_date_t !== '') { $where[] = "et.trans_date <= ?"; $params[] = $f_date_t; }
if ($f_status !== '') { $where[] = "et.status = ?"; $params[] = $f_status; }

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

$query = "
    SELECT et.*, ex.expense_name, cb.cashbox_name, u.username
    FROM expense_transactions et
    LEFT JOIN expenses ex ON et.expense_id = ex.expense_id
    LEFT JOIN cash_boxes cb ON et.box_id = cb.cashbox_id
    LEFT JOIN users u ON et.user_id = u.user_id
    $where_sql
    ORDER BY et.trans_date DESC
";

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

$total_Due = 0; $total_paid = 0;
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Expense Report - Print</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; font-size: 12px; color: #333; }
        .print-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #444; padding-bottom: 10px; margin-bottom: 20px; }
        .company-info h2 { margin: 0; color: #2c3e50; }
        .report-title { text-align: center; margin-bottom: 20px; }
        .report-title h3 { margin: 0; text-transform: uppercase; letter-spacing: 1px; }
        
        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        th { background: #f2f2f2; border: 1px solid #ccc; padding: 10px; text-align: left; }
        td { border: 1px solid #ccc; padding: 8px; }
        
        .summary-box { width: 300px; margin-left: auto; border: 1px solid #ccc; }
        .summary-row { display: flex; justify-content: space-between; padding: 8px; border-bottom: 1px solid #eee; }
        .summary-row:last-child { background: #f9f9f9; font-weight: bold; }
        
        .text-end { text-align: right; }
        .badge { font-weight: bold; }
        
        @media print {
            .no-print { display: none; }
            body { padding: 0; }
            @page { margin: 1.5cm; }
        }
    </style>
</head>
<body>

<div class="no-print" style="background: #fff3cd; padding: 10px; text-align: center; border: 1px solid #ffeeba; margin-bottom: 20px;">
    <button onclick="window.print()" style="padding: 10px 20px; cursor: pointer; background: #28a745; color: #fff; border: none; border-radius: 4px; font-weight: bold;">
        Click Here to Print
    </button>
    <p style="margin: 5px 0 0; font-size: 11px;">Note: Header and Footer are generated from Company Settings.</p>
</div>

<div class="print-header">
    <div class="company-info">
        <h2><?= htmlspecialchars($conf['company_name_en'] ?? 'My Company') ?></h2>
        <p><?= htmlspecialchars($conf['address_en'] ?? '') ?><br><?= htmlspecialchars($conf['phone'] ?? '') ?></p>
    </div>
    <div class="logo">
        <h1 style="color: #ccc;">LOGO</h1>
    </div>
</div>

<div class="report-title">
    <h3>Expense Transactions Report</h3>
    <p>Period: <?= $f_date_f ?: 'Beginning' ?> To <?= $f_date_t ?: 'Today' ?></p>
</div>

<table>
    <thead>
        <tr>
            <th>Date</th>
            <th>Category</th>
            <th>Description</th>
            <th>Box</th>
            <th>Status</th>
            <th class="text-end">Amount</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($transactions as $t): 
            $is_active = (strtolower($t['status']) == 'active');
            $amt = $t['amount'];
            if ($is_active) {
                if ($amt < 0) { $total_Due += abs($amt); $lbl = "Due"; }
                else { $total_paid += $amt; $lbl = "Paid"; }
            } else { $lbl = "Canceled"; }
        ?>
        <tr style="<?= !$is_active ? 'color: #aaa; text-decoration: line-through;' : '' ?>">
            <td><?= date('d/m/Y', strtotime($t['trans_date'])) ?></td>
            <td><strong><?= htmlspecialchars($t['expense_name']) ?></strong></td>
            <td><?= htmlspecialchars($t['description']) ?></td>
            <td><?= htmlspecialchars($t['cashbox_name']) ?></td>
            <td><?= $lbl ?></td>
            <td class="text-end"><?= number_format(abs($amt), 2) ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<div class="summary-box">
    <div class="summary-row">
        <span>Total Due:</span>
        <span><?= number_format($total_Due, 2) ?></span>
    </div>
    <div class="summary-row">
        <span>Total Paid:</span>
        <span><?= number_format($total_paid, 2) ?></span>
    </div>
    <div class="summary-row">
        <span>Net (Balance):</span>
        <span><?= number_format($total_paid - $total_Due, 2) ?></span>
    </div>
</div>

<div style="margin-top: 50px;">
    <table style="border: none;">
        <tr>
            <td style="border: none; text-align: center;">
                <p>Accountant Signature</p>
                <br>___________________
            </td>
            <td style="border: none; text-align: center;">
                <p>Manager Signature</p>
                <br>___________________
            </td>
        </tr>
    </table>
</div>

<script>
    // تلقائياً يفتح نافذة الطباعة عند التحميل (اختياري)
    // window.onload = function() { window.print(); }
</script>

</body>
</html>