<?php
if (session_status() === PHP_SESSION_NONE) session_start();

require_once '../config.php';

if (!isLoggedIn() || !isAdmin()) {
    setMessage('برای دسترسی به این صفحه، لطفاً به عنوان مدیر وارد شوید.', 'danger');
    redirect('/login.php');
}

$page_title = 'گزارشات مالی';

// --- Filtering Logic ---
$filters = [
    'representative_id' => $_GET['representative_id'] ?? 'all',
    'type' => $_GET['type'] ?? 'all',
    'date_from' => $_GET['date_from'] ?? '',
    'date_to' => $_GET['date_to'] ?? ''
];

$where_clauses = [];
$params = [];

if ($filters['representative_id'] !== 'all') {
    $where_clauses[] = "t.representative_id = ?";
    $params[] = $filters['representative_id'];
}
if ($filters['type'] !== 'all') {
    $where_clauses[] = "t.type = ?";
    $params[] = $filters['type'];
}
if (!empty($filters['date_from'])) {
    $where_clauses[] = "t.created_at >= ?";
    $params[] = $filters['date_from'] . ' 00:00:00';
}
if (!empty($filters['date_to'])) {
    $where_clauses[] = "t.created_at <= ?";
    $params[] = $filters['date_to'] . ' 23:59:59';
}

$where_sql = count($where_clauses) > 0 ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// --- Fetch Data ---
$transactions = [];
$summary = ['total_amount' => 0, 'total_count' => 0];

try {
    // Fetch transactions for the table
    $sql = "SELECT t.*, r.username FROM transactions t JOIN representatives r ON t.representative_id = r.id {$where_sql} ORDER BY t.created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $transactions = $stmt->fetchAll();

    // Fetch summary data
    $sql_summary = "SELECT COUNT(*) as total_count, COALESCE(SUM(amount), 0) as total_amount FROM transactions t {$where_sql}";
    $stmt_summary = $pdo->prepare($sql_summary);
    $stmt_summary->execute($params);
    $summary = $stmt_summary->fetch();

} catch (Exception $e) {
    setMessage('خطا در دریافت گزارشات: ' . $e->getMessage(), 'danger');
}

// Fetch representatives for the filter dropdown
$representatives = $pdo->query("SELECT id, username FROM representatives ORDER BY username")->fetchAll();

require_once '../includes/header.php';
?>

<!-- Filter Card -->
<div class="card admin-main-card mb-4">
    <div class="card-header">
        <h3 class="card-title mb-0"><i class="bi bi-funnel me-2"></i>فیلتر گزارشات</h3>
    </div>
    <div class="card-body">
        <form method="GET" action="reports.php" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label for="representative_id" class="form-label">نماینده</label>
                <select name="representative_id" id="representative_id" class="form-select">
                    <option value="all">همه نمایندگان</option>
                    <?php foreach ($representatives as $rep): ?>
                        <option value="<?= $rep['id'] ?>" <?= $filters['representative_id'] == $rep['id'] ? 'selected' : '' ?>><?= htmlspecialchars($rep['username']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label for="type" class="form-label">نوع تراکنش</label>
                <select name="type" id="type" class="form-select">
                    <option value="all">همه انواع</option>
                    <option value="deposit" <?= $filters['type'] == 'deposit' ? 'selected' : '' ?>>واریز</option>
                    <option value="withdrawal" <?= $filters['type'] == 'withdrawal' ? 'selected' : '' ?>>برداشت</option>
                    <option value="payment" <?= $filters['type'] == 'payment' ? 'selected' : '' ?>>پرداخت فاکتور</option>
                    <option value="refund" <?= $filters['type'] == 'refund' ? 'selected' : '' ?>>بازگشت وجه</option>
                </select>
            </div>
            <div class="col-md-3">
                <label for="date_from" class="form-label">از تاریخ</label>
                <input type="date" name="date_from" id="date_from" class="form-control" value="<?= htmlspecialchars($filters['date_from']) ?>">
            </div>
            <div class="col-md-3">
                <label for="date_to" class="form-label">تا تاریخ</label>
                <input type="date" name="date_to" id="date_to" class="form-control" value="<?= htmlspecialchars($filters['date_to']) ?>">
            </div>
            <div class="col-md-1">
                <button type="submit" class="btn btn-primary w-100">اعمال</button>
            </div>
        </form>
    </div>
</div>

<!-- Summary Cards -->
<div class="row mb-4">
    <div class="col-md-6">
        <div class="stat-card-v2">
            <div class="stat-icon icon-primary"><i class="bi bi-receipt"></i></div>
            <div class="stat-info">
                <h5>تعداد کل تراکنش‌ها</h5>
                <p><?= number_format($summary['total_count']) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="stat-card-v2">
            <div class="stat-icon icon-success"><i class="bi bi-cash-stack"></i></div>
            <div class="stat-info">
                <h5>جمع کل مبلغ تراکنش‌ها</h5>
                <p><?= number_format($summary['total_amount']) ?> <small>تومان</small></p>
            </div>
        </div>
    </div>
</div>

<!-- Results Table -->
<div class="card admin-main-card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?> — نتایج</h3>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>نماینده</th>
                        <th>مبلغ</th>
                        <th>نوع</th>
                        <th>توضیحات</th>
                        <th>تاریخ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transactions)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">هیچ تراکنشی با این فیلترها یافت نشد.</td></tr>
                    <?php else: ?>
                        <?php foreach ($transactions as $tx): ?>
                            <tr>
                                <td><?= htmlspecialchars($tx['username']) ?></td>
                                <td class="fw-bold text-<?= $tx['amount'] > 0 ? 'success' : 'danger' ?>">
                                    <?= number_format($tx['amount']) ?>
                                </td>
                                <td>
                                    <span class="badge bg-secondary-soft">
                                        <?php 
                                            switch ($tx['type']) {
                                                case 'deposit': echo 'واریز'; break;
                                                case 'withdrawal': echo 'برداشت'; break;
                                                case 'payment': echo 'پرداخت فاکتور'; break;
                                                case 'refund': echo 'بازگشت وجه'; break;
                                                default: echo htmlspecialchars($tx['type']);
                                            }
                                        ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($tx['description']) ?></td>
                                <td class="text-muted"><small><?= to_jalali($tx['created_at'], true) ?></small></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
