<?php
/**
 * Receipt Management - View and manage receipts
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/receipts.php';
requireAuth();
requirePermission('finance.view');

$pageTitle = 'Receipts';
$currentPage = 'finance';

// Ensure receipts table exists
try {
    $pdo->query('SELECT 1 FROM receipts LIMIT 1');
} catch (PDOException $e) {
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS receipts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                receipt_number VARCHAR(50) NOT NULL UNIQUE,
                transaction_id INT NOT NULL,
                member_id INT NULL,
                fund_id INT NOT NULL,
                amount DECIMAL(12,2) NOT NULL,
                transaction_date DATE NOT NULL,
                issued_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                issued_by INT NULL,
                emailed TINYINT(1) DEFAULT 0,
                emailed_at DATETIME NULL,
                notes TEXT NULL,
                INDEX idx_transaction_id (transaction_id),
                INDEX idx_receipt_number (receipt_number),
                INDEX idx_member_id (member_id),
                INDEX idx_issued_at (issued_at),
                FOREIGN KEY (transaction_id) REFERENCES transactions(id) ON DELETE CASCADE,
                FOREIGN KEY (member_id) REFERENCES members(id) ON DELETE SET NULL,
                FOREIGN KEY (fund_id) REFERENCES funds(id),
                FOREIGN KEY (issued_by) REFERENCES users(id) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (PDOException $e2) {
        // Ignore
    }
}

// Filters
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$filterMember = (int)($_GET['member_id'] ?? 0);
$filterReceiptNumber = trim($_GET['receipt_number'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 50;
$offset = ($page - 1) * $perPage;

// Build query
$where = [];
$params = [];

if ($filterDateFrom) {
    $where[] = 'r.transaction_date >= ?';
    $params[] = $filterDateFrom;
}

if ($filterDateTo) {
    $where[] = 'r.transaction_date <= ?';
    $params[] = $filterDateTo;
}

if ($filterMember > 0) {
    $where[] = 'r.member_id = ?';
    $params[] = $filterMember;
}

if ($filterReceiptNumber) {
    $where[] = 'r.receipt_number LIKE ?';
    $params[] = '%' . $filterReceiptNumber . '%';
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total count
$totalReceipts = 0;
$totalPages = 0;
$receipts = [];

try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM receipts r $whereClause");
    $countStmt->execute($params);
    $totalReceipts = (int)$countStmt->fetchColumn();
    $totalPages = ceil($totalReceipts / $perPage);
    
    // Get receipts
    $perPageInt = (int)$perPage;
    $offsetInt = (int)$offset;
    $stmt = $pdo->prepare("
        SELECT r.*, 
               f.name AS fund_name,
               m.first_name, m.last_name, m.email,
               CONCAT(m.first_name, ' ', m.last_name) AS member_name,
               u.username AS issued_by_username
        FROM receipts r
        JOIN funds f ON r.fund_id = f.id
        LEFT JOIN members m ON r.member_id = m.id
        LEFT JOIN users u ON r.issued_by = u.id
        $whereClause
        ORDER BY r.issued_at DESC
        LIMIT $perPageInt OFFSET $offsetInt
    ");
    $stmt->execute($params);
    $receipts = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log('Receipts query error: ' . $e->getMessage());
}

// Get members for filter
$members = [];
try {
    $members = $pdo->query('SELECT id, first_name, last_name FROM members ORDER BY last_name, first_name')->fetchAll();
} catch (PDOException $e) {
    // Ignore
}

// Statistics
$stats = [];
try {
    $stats['total'] = (int)$pdo->query('SELECT COUNT(*) FROM receipts')->fetchColumn();
    $stats['this_month'] = (int)$pdo->query("SELECT COUNT(*) FROM receipts WHERE MONTH(issued_at) = MONTH(NOW()) AND YEAR(issued_at) = YEAR(NOW())")->fetchColumn();
    $stats['emailed'] = (int)$pdo->query("SELECT COUNT(*) FROM receipts WHERE emailed = 1")->fetchColumn();
    $stats['total_amount'] = (float)$pdo->query('SELECT COALESCE(SUM(amount), 0) FROM receipts')->fetchColumn();
} catch (PDOException $e) {
    $stats = ['total' => 0, 'this_month' => 0, 'emailed' => 0, 'total_amount' => 0];
}

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

<div class="header">
    <h1>Receipts</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/finance" class="link-muted">← Finance</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- Statistics -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Receipts</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['total']) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">This Month</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['this_month']) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Emailed</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= number_format($stats['emailed']) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Total Amount</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;">GH&#8373; <?= number_format($stats['total_amount'], 2) ?></div>
    </div>
</div>

<!-- Filters -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Filters</h2>
    <form method="get" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; align-items: end;">
        <div>
            <label for="date_from" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">From Date</label>
            <input type="date" id="date_from" name="date_from" value="<?= htmlspecialchars($filterDateFrom) ?>" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <label for="date_to" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">To Date</label>
            <input type="date" id="date_to" name="date_to" value="<?= htmlspecialchars($filterDateTo) ?>" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <label for="member_id" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">Member</label>
            <select id="member_id" name="member_id" style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
                <option value="">All Members</option>
                <?php foreach ($members as $m): ?>
                <option value="<?= $m['id'] ?>" <?= $filterMember === $m['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars(trim($m['first_name'] . ' ' . $m['last_name'])) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label for="receipt_number" style="display: block; margin-bottom: 0.5rem; font-size: 0.875rem; color: #64748b;">Receipt Number</label>
            <input type="text" id="receipt_number" name="receipt_number" value="<?= htmlspecialchars($filterReceiptNumber) ?>" placeholder="Search..." style="width: 100%; padding: 0.5rem; border: 1px solid var(--border); border-radius: 4px;">
        </div>
        <div>
            <button type="submit" class="btn" style="width: 100%;">Apply Filters</button>
        </div>
    </form>
    <?php if ($filterDateFrom || $filterDateTo || $filterMember || $filterReceiptNumber): ?>
    <p style="margin-top: 1rem;">
        <a href="<?= BASE_PATH ?>/finance/receipts" class="btn btn-sm btn-ghost">Clear Filters</a>
    </p>
    <?php endif; ?>
</div>

<!-- Transactions Without Receipts -->
<?php
// Get recent transactions without receipts
$transactionsWithoutReceipts = [];
try {
    $noReceiptStmt = $pdo->prepare("
        SELECT t.id, t.transaction_date, t.amount, t.note,
               f.name AS fund_name,
               m.first_name, m.last_name,
               CONCAT(m.first_name, ' ', m.last_name) AS member_name
        FROM transactions t
        JOIN funds f ON t.fund_id = f.id
        LEFT JOIN members m ON t.member_id = m.id
        LEFT JOIN receipts r ON t.id = r.transaction_id
        WHERE r.id IS NULL
        ORDER BY t.transaction_date DESC, t.id DESC
        LIMIT 10
    ");
    $noReceiptStmt->execute();
    $transactionsWithoutReceipts = $noReceiptStmt->fetchAll();
} catch (PDOException $e) {
    // Ignore if receipts table doesn't exist yet
}
?>

<?php if (!empty($transactionsWithoutReceipts)): ?>
<div class="card" style="border-left: 4px solid #f59e0b; margin-bottom: 1.5rem;">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">
        Transactions Without Receipts
        <span style="font-size: 0.875rem; font-weight: 400; color: #64748b; margin-left: 0.5rem;">
            (<?= count($transactionsWithoutReceipts) ?> recent)
        </span>
    </h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Member</th>
                    <th>Fund</th>
                    <th style="text-align: right;">Amount</th>
                    <th style="text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactionsWithoutReceipts as $tx): ?>
                <tr>
                    <td style="color: #64748b;"><?= date('M j, Y', strtotime($tx['transaction_date'])) ?></td>
                    <td>
                        <?php if ($tx['member_name']): ?>
                        <?= htmlspecialchars($tx['member_name']) ?>
                        <?php else: ?>
                        <span style="color: #94a3b8;">—</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($tx['fund_name']) ?></td>
                    <td style="text-align: right; font-weight: 500;">GH&#8373; <?= number_format($tx['amount'], 2) ?></td>
                    <td style="text-align: center;">
                        <a href="<?= BASE_PATH ?>/finance/receipts/generate/<?= $tx['id'] ?>" class="btn btn-sm" title="Generate Receipt">
                            Generate Receipt
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Receipts Table -->
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">
        Receipt History
        <span style="font-size: 0.875rem; font-weight: 400; color: #64748b; margin-left: 0.5rem;">
            (<?= number_format($totalReceipts) ?> total)
        </span>
    </h2>
    
    <?php if (empty($receipts)): ?>
    <p class="text-muted">No receipts found.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Receipt #</th>
                    <th>Date</th>
                    <th>Member</th>
                    <th>Fund</th>
                    <th style="text-align: right;">Amount</th>
                    <th>Status</th>
                    <th style="text-align: center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($receipts as $receipt): ?>
                <tr>
                    <td style="font-family: monospace; font-weight: 500;"><?= htmlspecialchars($receipt['receipt_number']) ?></td>
                    <td style="color: #64748b;"><?= date('M j, Y', strtotime($receipt['transaction_date'])) ?></td>
                    <td>
                        <?php if ($receipt['member_name']): ?>
                        <?= htmlspecialchars($receipt['member_name']) ?>
                        <?php else: ?>
                        <span style="color: #94a3b8;">—</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($receipt['fund_name']) ?></td>
                    <td style="text-align: right; font-weight: 500;">GH&#8373; <?= number_format($receipt['amount'], 2) ?></td>
                    <td>
                        <?php if ($receipt['emailed']): ?>
                        <span style="color: #10b981; font-size: 0.875rem;">✓ Emailed</span>
                        <?php else: ?>
                        <span style="color: #64748b; font-size: 0.875rem;">Not emailed</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align: center;">
                        <a href="<?= BASE_PATH ?>/finance/receipts/print/<?= $receipt['id'] ?>" target="_blank" class="btn-icon" title="Print Receipt">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
                            </svg>
                        </a>
                        <?php if ($receipt['member_id'] && !empty($receipt['email'])): ?>
                        <a href="<?= BASE_PATH ?>/finance/receipts/email/<?= $receipt['id'] ?>" class="btn-icon" title="Email Receipt">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                            </svg>
                        </a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div style="margin-top: 1.5rem; display: flex; justify-content: center; align-items: center; gap: 0.5rem;">
        <?php if ($page > 1): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" class="btn btn-sm btn-outline">← Previous</a>
        <?php endif; ?>
        <span style="color: #64748b;">Page <?= $page ?> of <?= $totalPages ?></span>
        <?php if ($page < $totalPages): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" class="btn btn-sm btn-outline">Next →</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>

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