<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$customerId = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;
$customer = null;
$payments = [];
$sales = [];

// Minimal ledger-style view: opening balance (before from date), transactions in range, closing outstanding
    // Fetch customer details
    $stmt = mysqli_prepare($con, "SELECT ID, CustomerName, Mobile, Area, CustomerType FROM tblcustomers WHERE ID = ? AND IsActive = 1");
    mysqli_stmt_bind_param($stmt, 'i', $customerId);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $customer = mysqli_fetch_assoc($res);

    // Get filter parameters
    $filterType = isset($_GET['type']) ? $_GET['type'] : 'all'; // all, credit, debit
    $filterMethod = isset($_GET['method']) ? $_GET['method'] : 'all';
    $period = isset($_GET['period']) ? $_GET['period'] : 'this_month'; // all, this_month, last_6_months, this_year, custom
    $fromParam = isset($_GET['from']) ? $_GET['from'] : '';
    $toParam = isset($_GET['to']) ? $_GET['to'] : '';

    // Compute date range boundaries
    $fromDate = null; // inclusive start datetime (Y-m-d H:i:s)
    $toDateExclusive = null; // exclusive end datetime (Y-m-d H:i:s)

    date_default_timezone_set('Asia/Kolkata');
    $today = new DateTime('today');

    if ($period === 'this_month') {
        $start = new DateTime('first day of this month 00:00:00');
        $end = (clone $start)->modify('first day of next month 00:00:00');
        $fromDate = $start->format('Y-m-d H:i:s');
        $toDateExclusive = $end->format('Y-m-d H:i:s');
    } elseif ($period === 'last_6_months') {
        $start = (clone $today)->modify('-6 months');
        $start->setTime(0,0,0);
        $end = (clone $today)->modify('+1 day')->setTime(0,0,0);
        $fromDate = $start->format('Y-m-d H:i:s');
        $toDateExclusive = $end->format('Y-m-d H:i:s');
    } elseif ($period === 'this_year') {
        $yearStart = new DateTime(date('Y-01-01 00:00:00'));
        $nextYearStart = (clone $yearStart)->modify('+1 year');
        $fromDate = $yearStart->format('Y-m-d H:i:s');
        $toDateExclusive = $nextYearStart->format('Y-m-d H:i:s');
    } elseif ($period === 'custom' && $fromParam && $toParam) {
        // Expect Y-m-d
        $start = DateTime::createFromFormat('Y-m-d H:i:s', $fromParam . ' 00:00:00');
        $end = DateTime::createFromFormat('Y-m-d H:i:s', $toParam . ' 00:00:00');
        if ($start && $end) {
            $fromDate = $start->format('Y-m-d H:i:s');
            // exclusive end is next day after 'to'
            $toDateExclusive = $end->modify('+1 day')->format('Y-m-d H:i:s');
        }
    } else {
        // 'all' or invalid -> no date filter
        $fromDate = null;
        $toDateExclusive = null;
    }

    // Opening balance: sum before fromDate (if fromDate set)
    $openingBalance = 0.0;
    if ($customerId > 0 && $fromDate) {
        $openSql = "SELECT 
                        COALESCE(SUM(CASE WHEN TransactionType = 'Debit' AND Status='Completed' THEN Amount ELSE 0 END), 0) AS Debits,
                        COALESCE(SUM(CASE WHEN TransactionType = 'Credit' AND Status='Completed' THEN (CASE WHEN PaidAmount > 0 THEN PaidAmount ELSE Amount END) ELSE 0 END), 0) AS Credits
                    FROM tblcustomerpayments
                    WHERE CustomerID = ? AND IsActive = 1 AND TransactionDate < ?";
        $stmt = mysqli_prepare($con, $openSql);
        mysqli_stmt_bind_param($stmt, 'is', $customerId, $fromDate);
        mysqli_stmt_execute($stmt);
        $res = mysqli_stmt_get_result($stmt);
        if ($row = mysqli_fetch_assoc($res)) {
            $openingBalance = (float)$row['Debits'] - (float)$row['Credits'];
        }
    }

    // Fetch transactions within range
    $conditions = ["CustomerID = ?", "IsActive = 1", "Status = 'Completed'"];
    $bind = [$customerId];
    $bindTypes = 'i';

    if ($filterType !== 'all') {
        $conditions[] = "TransactionType = ?";
        $bind[] = ucfirst($filterType);
        $bindTypes .= 's';
    }
    if ($filterMethod !== 'all') {
        $conditions[] = "PaymentMethod = ?";
        $bind[] = $filterMethod;
        $bindTypes .= 's';
    }
    if ($fromDate && $toDateExclusive) {
        $conditions[] = "TransactionDate >= ? AND TransactionDate < ?";
        $bind[] = $fromDate;
        $bind[] = $toDateExclusive;
        $bindTypes .= 'ss';
    }

    $whereClause = 'WHERE ' . implode(' AND ', $conditions);
    $txSql = "SELECT ID, TransactionType, TransactionDate, Amount, PaidAmount, PaymentMethod, ReferenceNumber, Description
              FROM tblcustomerpayments
              $whereClause
              ORDER BY TransactionDate ASC, ID ASC";
    $stmt = mysqli_prepare($con, $txSql);
    mysqli_stmt_bind_param($stmt, $bindTypes, ...$bind);
    mysqli_stmt_execute($stmt);
    $transactions = mysqli_stmt_get_result($stmt);

    // Compute period totals and closing
    $periodCredits = 0.0; $periodDebits = 0.0; $rows = [];
    if ($transactions) {
        while ($txn = mysqli_fetch_assoc($transactions)) {
            $isCredit = $txn['TransactionType'] === 'Credit';
            $paid = isset($txn['PaidAmount']) ? (float)$txn['PaidAmount'] : 0.0;
            $amt  = isset($txn['Amount']) ? (float)$txn['Amount'] : 0.0;
            $amount = $isCredit ? ($paid > 0 ? $paid : $amt) : $amt;
            if ($isCredit) { $periodCredits += $amount; } else { $periodDebits += $amount; }
            $txn['__DisplayAmount'] = $amount;
            $rows[] = $txn;
        }
    }
    $closingOutstanding = $openingBalance + ($periodDebits - $periodCredits);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Transaction History</title>
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        * { 
            box-sizing: border-box; 
            -webkit-tap-highlight-color: transparent; 
        }
        
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #1a1a1a; 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 
            margin: 0; 
            padding: 0; 
            min-height: 100vh;
            line-height: 1.5;
        }
        
        .header { 
            background: rgba(255, 255, 255, 0.95); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            color: #1a1a1a; 
            padding: 16px 20px; 
            display: flex; 
            align-items: center; 
            gap: 16px; 
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .back-btn { 
            background: rgba(103, 126, 234, 0.1); 
            border: none; 
            color: #667eea; 
            font-size: 20px; 
            cursor: pointer; 
            width: 40px; 
            height: 40px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            transition: all 0.2s ease;
        }
        
        .back-btn:hover {
            background: rgba(103, 126, 234, 0.2);
            transform: scale(1.05);
        }
        
        .dashboard-btn { 
            background: rgba(103, 126, 234, 0.1); 
            border: none; 
            color: #667eea; 
            font-size: 18px; 
            cursor: pointer; 
            width: 40px; 
            height: 40px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            transition: all 0.2s ease;
            margin-left: 8px;
        }
        
        .dashboard-btn:hover {
            background: rgba(103, 126, 234, 0.2);
            transform: scale(1.05);
        }
        
        .title { 
            font-size: 22px; 
            margin: 0; 
            font-weight: 700; 
            color: #1a1a1a;
        }
        
        .customer-chip { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #fff; 
            padding: 8px 16px; 
            border-radius: 20px; 
            font-size: 13px; 
            font-weight: 600; 
            margin-left: auto;
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.3);
        }
        
        .container { 
            max-width: 800px; 
            margin: 0 auto; 
            padding: 20px 16px; 
        }
        
        .card { 
            background: rgba(255, 255, 255, 0.95); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2); 
            border-radius: 16px; 
            overflow: hidden; 
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); 
            margin-bottom: 20px;
            transition: transform 0.2s ease;
        }
        
        .card:hover {
            transform: translateY(-2px);
        }
        
        .card h3 { 
            font-size: 16px; 
            margin: 0; 
            padding: 16px 20px; 
            border-bottom: 1px solid rgba(0, 0, 0, 0.06); 
            font-weight: 700;
            color: #1a1a1a;
        }
        
        .summary { 
            padding: 16px 20px; 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); 
            gap: 12px; 
        }
        
        .pill { 
            background: linear-gradient(135deg, rgba(103, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%); 
            padding: 12px; 
            border-radius: 10px; 
            font-size: 12px; 
            font-weight: 600; 
            border: 1px solid rgba(103, 126, 234, 0.1);
            text-align: center;
            transition: all 0.2s ease;
        }
        
        .pill:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.15);
        }
        
        .pill .label { 
            color: #667eea; 
            font-weight: 600; 
            display: block; 
            font-size: 12px; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
            margin-bottom: 4px; 
        }
        
        .pill .value {
            color: #1a1a1a;
            font-size: 14px;
            font-weight: 700;
        }
        
        .filters { 
            padding: 16px 20px; 
            background: rgba(103, 126, 234, 0.05); 
            border-bottom: 1px solid rgba(0, 0, 0, 0.06); 
            display: flex; 
            flex-wrap: wrap;
            gap: 12px; 
            align-items: end; 
        }
        
        .filter-group { 
            display: flex; 
            flex-direction: column; 
            gap: 6px; 
            transition: all 0.3s ease;
            min-width: 100px;
            max-width: 140px;
        }
        
        .filter-label { 
            font-size: 11px; 
            color: #667eea; 
            font-weight: 600; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
        }
        
        .filter-select, .filter-input { 
            padding: 8px 10px; 
            border: 2px solid rgba(103, 126, 234, 0.1); 
            border-radius: 8px; 
            font-size: 13px; 
            background: rgba(255, 255, 255, 0.8); 
            transition: all 0.2s ease;
            font-weight: 500;
            width: 100%;
            min-width: 0;
        }
        
        .filter-select:focus, .filter-input:focus { 
            outline: none; 
            border-color: #667eea; 
            background: rgba(255, 255, 255, 0.95);
            box-shadow: 0 0 0 3px rgba(103, 126, 234, 0.1);
        }
        
        .print-btn { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #fff; 
            border: none; 
            padding: 8px 16px; 
            border-radius: 8px; 
            font-size: 12px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.2s ease;
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.3);
            margin-left: auto;
            flex-shrink: 0;
        }
        
        .print-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(103, 126, 234, 0.4);
        }
        
        .txn-list { 
            list-style: none; 
            padding: 0; 
            margin: 0; 
        }
        
        .txn-item { 
            display: flex; 
            align-items: center; 
            gap: 12px; 
            padding: 16px 20px; 
            border-bottom: 1px solid rgba(0, 0, 0, 0.04); 
            transition: all 0.2s ease;
        }
        
        .txn-item:hover {
            background: rgba(103, 126, 234, 0.02);
        }
        
        .txn-item:last-child { 
            border-bottom: none; 
        }
        
        .txn-icon { 
            width: 40px; 
            height: 40px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            color: #fff; 
            font-size: 16px; 
            flex-shrink: 0;
        }
        
        .txn-icon.credit { 
            background: linear-gradient(135deg, #10b981 0%, #059669 100%); 
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        
        .txn-icon.debit { 
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); 
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }
        
        .txn-main { 
            flex: 1; 
            min-width: 0;
        }
        
        .txn-title { 
            font-weight: 600; 
            font-size: 14px; 
            color: #1a1a1a; 
            margin-bottom: 2px;
        }
        
        .txn-sub { 
            font-size: 12px; 
            color: #6b7280; 
            line-height: 1.3;
        }
        
        .txn-sub a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            border-bottom: 1px solid rgba(103, 126, 234, 0.3);
            transition: all 0.2s ease;
        }
        
        .txn-sub a:hover {
            border-bottom-color: #667eea;
        }
        
        .txn-amount { 
            font-weight: 700; 
            font-size: 16px; 
            text-align: right;
            flex-shrink: 0;
        }
        
        .amt-credit { 
            color: #10b981; 
        }
        
        .amt-debit { 
            color: #ef4444; 
        }
        
        .empty { 
            text-align: center; 
            color: #6b7280; 
            padding: 48px 24px; 
            font-size: 16px;
        }
        
        .empty i {
            font-size: 48px;
            margin-bottom: 16px;
            display: block;
            opacity: 0.5;
        }
        
        /* Mobile optimizations */
        @media (max-width: 768px) {
            .header {
                padding: 12px 16px;
            }
            
            .title {
                font-size: 18px;
            }
            
            .customer-chip {
                font-size: 11px;
                padding: 6px 12px;
            }
            
            .container {
                padding: 16px 12px;
            }
            
            .card h3 {
                padding: 14px 16px;
                font-size: 15px;
            }
            
            .summary {
                padding: 14px 16px;
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }
            
            .pill {
                padding: 10px;
                font-size: 11px;
            }
            
            .pill .value {
                font-size: 13px;
            }
            
            .filters {
                padding: 14px 16px;
                gap: 10px;
            }
            
            .filter-group {
                min-width: 90px;
                max-width: 120px;
            }
            
            .filter-select, .filter-input {
                padding: 7px 8px;
                font-size: 14px; /* Prevent zoom on iOS */
            }
            
            .print-btn {
                padding: 7px 12px;
                font-size: 11px;
            }
            
            .txn-item {
                padding: 14px 16px;
                gap: 10px;
            }
            
            .txn-icon {
                width: 36px;
                height: 36px;
                font-size: 14px;
            }
            
            .txn-title {
                font-size: 13px;
            }
            
            .txn-sub {
                font-size: 11px;
            }
            
            .txn-amount {
                font-size: 15px;
            }
        }
        
        @media (max-width: 480px) {
            .summary {
                grid-template-columns: 1fr;
            }
            
            .pill {
                text-align: left;
                padding: 8px;
            }
            
            .filters {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                max-width: none;
            }
            
            .print-btn {
                margin-left: 0;
                align-self: center;
                width: 120px;
            }
            
            .txn-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
                padding: 12px 16px;
            }
            
            .txn-amount {
                align-self: flex-end;
                font-size: 16px;
            }
        }
        
        @media print {
            .header, .filters, .print-btn { display: none; }
            body { background: #fff; }
            .card { box-shadow: none; border: none; }
        }
    </style>
</head>
<body>
    <div class="header">
        <button class="back-btn" onclick="history.back()" title="Back"><i class="fas fa-arrow-left"></i></button>
        <h1 class="title">Transactions</h1>
        <button class="dashboard-btn" onclick="window.location.href='dashboard.php'" title="Dashboard">
            <i class="fas fa-tachometer-alt"></i>
        </button>
        <?php if ($customer): ?>
        <div class="customer-chip"><i class="fas fa-user mr-1"></i> <?= htmlspecialchars($customer['CustomerName']) ?></div>
        <?php endif; ?>
    </div>

    <div class="container">
        <?php if (!$customerId || !$customer): ?>
            <div class="card">
                <div class="empty">
                    <i class="fas fa-user-slash"></i>
                    No customer selected or customer not found.
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <h3>Transaction History</h3>
                
                <!-- Quick Filters -->
                <div class="filters">
                    <div class="filter-group">
                        <label class="filter-label">Type</label>
                        <select class="filter-select" id="typeFilter">
                            <option value="all" <?= $filterType === 'all' ? 'selected' : '' ?>>All</option>
                            <option value="credit" <?= $filterType === 'credit' ? 'selected' : '' ?>>Credits</option>
                            <option value="debit" <?= $filterType === 'debit' ? 'selected' : '' ?>>Debits</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">Method</label>
                        <select class="filter-select" id="methodFilter">
                            <option value="all" <?= $filterMethod === 'all' ? 'selected' : '' ?>>All Methods</option>
                            <option value="Cash" <?= $filterMethod === 'Cash' ? 'selected' : '' ?>>Cash</option>
                            <option value="Bank Transfer" <?= $filterMethod === 'Bank Transfer' ? 'selected' : '' ?>>Bank Transfer</option>
                            <option value="UPI" <?= $filterMethod === 'UPI' ? 'selected' : '' ?>>UPI</option>
                            <option value="Cheque" <?= $filterMethod === 'Cheque' ? 'selected' : '' ?>>Cheque</option>
                            <option value="Card" <?= $filterMethod === 'Card' ? 'selected' : '' ?>>Card</option>
                            <option value="Online" <?= $filterMethod === 'Online' ? 'selected' : '' ?>>Online</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">Period</label>
                        <select class="filter-select" id="periodFilter">
                            <option value="this_month" <?= $period === 'this_month' ? 'selected' : '' ?>>This Month</option>
                            <option value="last_6_months" <?= $period === 'last_6_months' ? 'selected' : '' ?>>Last 6 Months</option>
                            <option value="this_year" <?= $period === 'this_year' ? 'selected' : '' ?>>This Year</option>
                            <option value="all" <?= $period === 'all' ? 'selected' : '' ?>>All Time</option>
                            <option value="custom" <?= $period === 'custom' ? 'selected' : '' ?>>Custom Range</option>
                        </select>
                    </div>
                    <div class="filter-group" id="customDates" style="display: <?= $period === 'custom' ? 'block' : 'none' ?>; max-width: 200px;">
                        <label class="filter-label">Date Range</label>
                        <div style="display: flex; gap: 6px; align-items: center;">
                            <input type="date" class="filter-input" id="fromDate" value="<?= htmlspecialchars($fromParam) ?>" style="flex: 1; font-size: 11px;">
                            <span style="color: #667eea; font-weight: 600; font-size: 11px;">to</span>
                            <input type="date" class="filter-input" id="toDate" value="<?= htmlspecialchars($toParam) ?>" style="flex: 1; font-size: 11px;">
                        </div>
                    </div>
                    <!-- Auto-apply on change; no button needed -->
                    <button class="print-btn" onclick="printTransactions()"><i class="fas fa-print mr-1"></i>Print</button>
                </div>

                <!-- Opening/Closing Summary -->
                <div class="summary">
                    <div class="pill">
                        <span class="label">Opening Balance</span>
                        <div class="value">₹<?= number_format($openingBalance, 2) ?></div>
                    </div>
                    <div class="pill">
                        <span class="label">Credits Received</span>
                        <div class="value">+₹<?= number_format($periodCredits, 2) ?></div>
                    </div>
                    <div class="pill">
                        <span class="label">Debits Made</span>
                        <div class="value">-₹<?= number_format($periodDebits, 2) ?></div>
                    </div>
                    <div class="pill" style="background: linear-gradient(135deg, rgba(103, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%); border-color: rgba(103, 126, 234, 0.2);">
                        <span class="label">Outstanding Balance</span>
                        <div class="value" style="color: #667eea;">₹<?= number_format($closingOutstanding, 2) ?></div>
                    </div>
                </div>
                
                <ul class="txn-list">
                    <?php $any = count($rows) > 0; foreach ($rows as $txn): $isCredit = $txn['TransactionType'] === 'Credit'; $amount = $txn['__DisplayAmount']; ?>
                        <li class="txn-item">
                            <div class="txn-icon <?= $isCredit ? 'credit' : 'debit' ?>">
                                <i class="fas <?= $isCredit ? 'fa-arrow-down' : 'fa-arrow-up' ?>"></i>
                            </div>
                            <div class="txn-main">
                                <div class="txn-title">
                                    <?= $isCredit ? 'Payment Received' : 'Payment Made' ?> - <?= htmlspecialchars($txn['PaymentMethod']) ?>
                                </div>
                                <div class="txn-sub">
                                    <?= htmlspecialchars($txn['TransactionDate']) ?>
                                    <?php if ($txn['ReferenceNumber']): ?> • Ref: <a href="#" onclick="openInvoiceModal('<?= htmlspecialchars($txn['ReferenceNumber']) ?>'); return false;"><?= htmlspecialchars($txn['ReferenceNumber']) ?></a><?php endif; ?>
                                    <?php if ($txn['Description']): ?> <br><small style="color:#858796;"><?= htmlspecialchars(substr($txn['Description'], 0, 60)) ?><?= strlen($txn['Description']) > 60 ? '...' : '' ?></small><?php endif; ?>
                                </div>
                            </div>
                            <div class="txn-amount <?= $isCredit ? 'amt-credit' : 'amt-debit' ?>">
                                <?= $isCredit ? '+' : '-' ?>₹<?= number_format($amount, 2) ?>
                            </div>
                        </li>
                    <?php endforeach; ?>

                    <?php if (!$any): ?>
                        <li class="empty">
                            <i class="fas fa-receipt"></i>
                            No transactions found for the selected filters.
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function applyFilters() {
            // Show loading state
            const container = document.querySelector('.container');
            if (container) {
                container.style.opacity = '0.7';
                container.style.pointerEvents = 'none';
            }
            
            const urlParams = new URLSearchParams(window.location.search);
            const customerId = urlParams.get('customer_id');
            
            const type = document.getElementById('typeFilter').value;
            const method = document.getElementById('methodFilter').value;
            const period = document.getElementById('periodFilter').value;
            const from = document.getElementById('fromDate')?.value || '';
            const to = document.getElementById('toDate')?.value || '';
            
            let url = `transaction-history.php?customer_id=${customerId}`;
            if (type !== 'all') url += `&type=${type}`;
            if (method !== 'all') url += `&method=${encodeURIComponent(method)}`;
            url += `&period=${period}`;
            if (period === 'custom') {
                if (from) url += `&from=${from}`;
                if (to) url += `&to=${to}`;
            }
            
            window.location.href = url;
        }
        // Invoice view modal (restored)
        function ensureInvoiceModal() {
            if (document.getElementById('invoiceModal')) return;
            const modal = document.createElement('div');
            modal.id = 'invoiceModal';
            modal.style.position = 'fixed';
            modal.style.inset = '0';
            modal.style.background = 'rgba(0,0,0,0.4)';
            modal.style.display = 'none';
            modal.style.zIndex = '9999';
            modal.innerHTML = `
                <div style="max-width: 720px; width: 95%; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); overflow: hidden;">
                    <div style="display:flex; align-items:center; justify-content:space-between; padding:12px 16px; background:#232F3E; color:#fff;">
                        <div style="font-weight:700;">Invoice Details</div>
                        <button onclick="closeInvoiceModal()" style="background:transparent; border:none; color:#fff; font-size:18px; cursor:pointer;">✕</button>
                    </div>
                    <div id="invoiceBody" style="padding: 12px 16px; max-height: 70vh; overflow:auto;"></div>
                    <div style="padding:10px 16px; text-align:right; border-top:1px solid #eee;">
                        <button onclick="closeInvoiceModal()" class="btn btn-secondary btn-sm">Close</button>
                    </div>
                </div>`;
            document.body.appendChild(modal);
            modal.addEventListener('click', (e) => { if (e.target === modal) closeInvoiceModal(); });
        }

        function openInvoiceModal(saleNumber) {
            ensureInvoiceModal();
            const modal = document.getElementById('invoiceModal');
            const body = document.getElementById('invoiceBody');
            modal.style.display = 'block';
            body.innerHTML = `<div>Loading ${saleNumber}...</div>`;
            fetch(`api/get-sale-by-number.php?sale_number=${encodeURIComponent(saleNumber)}&include_items=true`)
                .then(r => r.json())
                .then(json => {
                    if (!json.success) throw new Error(json.message || 'Failed to load');
                    const s = json.data;
                    const items = (s.items || []).map(it => `
                        <tr>
                            <td>${it.ProductName || ''}</td>
                            <td class="text-right">${Number(it.Quantity).toLocaleString('en-IN')}</td>
                            <td class="text-right">₹${Number(it.UnitPrice).toLocaleString('en-IN', {minimumFractionDigits:2})}</td>
                            <td class="text-right">₹${Number(it.LineTotal).toLocaleString('en-IN', {minimumFractionDigits:2})}</td>
                        </tr>
                    `).join('');
                    body.innerHTML = `
                        <div style="display:flex; gap:16px; flex-wrap:wrap;">
                            <div style="flex:1; min-width: 220px;">
                                <div><strong>Sale No:</strong> ${s.SaleNumber}</div>
                                <div><strong>Date:</strong> ${s.SaleDate} ${s.SaleTime || ''}</div>
                                <div><strong>Customer:</strong> ${s.CustomerName || ''}</div>
                                <div><strong>Mobile:</strong> ${s.Mobile || ''}</div>
                                <div><strong>Area:</strong> ${s.Area || ''}</div>
                            </div>
                            <div style="min-width: 220px;">
                                <div><strong>Payment:</strong> ${s.PaymentMethod || ''} (${s.PaymentStatus || ''})</div>
                                <div><strong>Subtotal:</strong> ₹${Number(s.SubTotal).toLocaleString('en-IN', {minimumFractionDigits:2})}</div>
                                <div><strong>Discount:</strong> ₹${Number(s.DiscountAmount).toLocaleString('en-IN', {minimumFractionDigits:2})}</div>
                                <div><strong>Total:</strong> ₹${Number(s.TotalAmount).toLocaleString('en-IN', {minimumFractionDigits:2})}</div>
                                <div><strong>Paid:</strong> ₹${Number(s.PaidAmount).toLocaleString('en-IN', {minimumFractionDigits:2})}</div>
                                <div><strong>Balance:</strong> ₹${Number(s.BalanceAmount).toLocaleString('en-IN', {minimumFractionDigits:2})}</div>
                            </div>
                        </div>
                        <hr/>
                        <div style="overflow-x:auto;">
                            <table class="table table-sm" style="font-size: 13px;">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th class="text-right">Qty</th>
                                        <th class="text-right">Rate</th>
                                        <th class="text-right">Total</th>
                                    </tr>
                                </thead>
                                <tbody>${items || ''}</tbody>
                            </table>
                        </div>
                        ${s.Notes ? `<div><strong>Notes:</strong> ${s.Notes}</div>` : ''}
                    `;
                })
                .catch(err => {
                    body.innerHTML = `<div style="color:#dc3545;">${err.message}</div>`;
                });
        }

        function closeInvoiceModal() {
            const modal = document.getElementById('invoiceModal');
            if (modal) modal.style.display = 'none';
        }

        // Auto-apply filters on change
        (function(){
            const typeSel = document.getElementById('typeFilter');
            const methodSel = document.getElementById('methodFilter');
            const periodSel = document.getElementById('periodFilter');
            const customWrap = document.getElementById('customDates');
            const fromEl = document.getElementById('fromDate');
            const toEl = document.getElementById('toDate');

            function onPeriodChange(){
                const isCustom = periodSel.value === 'custom';
                customWrap.style.display = isCustom ? 'block' : 'none';
                if (!isCustom) applyFilters();
            }

            function onCustomChange(){
                if (periodSel.value !== 'custom') return;
                if (fromEl && toEl && fromEl.value && toEl.value) {
                    applyFilters();
                }
            }

            typeSel && typeSel.addEventListener('change', applyFilters);
            methodSel && methodSel.addEventListener('change', applyFilters);
            periodSel && periodSel.addEventListener('change', onPeriodChange);
            fromEl && fromEl.addEventListener('change', onCustomChange);
            toEl && toEl.addEventListener('change', onCustomChange);
        })();

        // Print function (restored and adapted)
        function printTransactions() {
            const customerName = '<?= htmlspecialchars($customer['CustomerName'] ?? '') ?>';
            const customerMobile = '<?= htmlspecialchars($customer['Mobile'] ?? '') ?>';
            const customerArea = '<?= htmlspecialchars($customer['Area'] ?? '') ?>';
            const opening = <?= json_encode(number_format($openingBalance, 2, '.', '')) ?>;
            const pCredits = <?= json_encode(number_format($periodCredits, 2, '.', '')) ?>;
            const pDebits = <?= json_encode(number_format($periodDebits, 2, '.', '')) ?>;
            const closing = <?= json_encode(number_format($closingOutstanding, 2, '.', '')) ?>;
            
            // Get current filter values for display
            const filterType = document.getElementById('typeFilter').value;
            const filterMethod = document.getElementById('methodFilter').value;
            const period = document.getElementById('periodFilter').value;
            const fromDate = document.getElementById('fromDate')?.value || '';
            const toDate = document.getElementById('toDate')?.value || '';
            
            // Format period display
            let periodText = '';
            switch(period) {
                case 'this_month': periodText = 'This Month'; break;
                case 'last_6_months': periodText = 'Last 6 Months'; break;
                case 'this_year': periodText = 'This Year'; break;
                case 'custom': 
                    if (fromDate && toDate) {
                        periodText = `${fromDate} to ${toDate}`;
                    } else {
                        periodText = 'Custom Range';
                    }
                    break;
                default: periodText = 'All Time'; break;
            }
            
            const filterTypeText = filterType === 'all' ? 'All Types' : (filterType === 'credit' ? 'Credits Only' : 'Debits Only');
            const filterMethodText = filterMethod === 'all' ? 'All Methods' : filterMethod;
            
            const currentDate = new Date().toLocaleDateString('en-IN', {
                day: '2-digit',
                month: '2-digit', 
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });

            let printContent = `
                <style>
                    @media print {
                        body { font-family: 'Courier New', monospace; font-size: 10px; margin: 0; padding: 2mm; width: 58mm; background: #fff; }
                        .center { text-align: center; }
                        .left { text-align: left; }
                        .right { text-align: right; }
                        .row { display:flex; justify-content:space-between; margin:1px 0; }
                        .dash { border-top: 1px dashed #000; margin: 4px 0; }
                        .bold { font-weight: bold; }
                        .small { font-size: 8px; }
                        .medium { font-size: 9px; }
                    }
                    @page { margin: 2mm; }
                </style>
                <div class="center bold">TRANSACTION STATEMENT</div>
                <div class="center medium">${customerName}</div>
                <div class="center small">${customerMobile}</div>
                ${customerArea ? `<div class="center small">${customerArea}</div>` : ''}
                <div class="dash"></div>
                <div class="center small bold">FILTER DETAILS</div>
                <div class="small">Period: ${periodText}</div>
                <div class="small">Type: ${filterTypeText}</div>
                <div class="small">Method: ${filterMethodText}</div>
                <div class="small">Generated: ${currentDate}</div>
                <div class="dash"></div>
                <div class="center small bold">BALANCE SUMMARY</div>
                <div class="row"><span>Opening Balance</span><span>₹${opening}</span></div>
                <div class="row"><span>Period Credits</span><span>+₹${pCredits}</span></div>
                <div class="row"><span>Period Debits</span><span>-₹${pDebits}</span></div>
                <div class="dash"></div>
                <div class="row bold"><span>Closing Outstanding</span><span>₹${closing}</span></div>
                <div class="dash"></div>
                <div class="center small bold">TRANSACTION DETAILS</div>
            `;

            const items = document.querySelectorAll('.txn-item');
            if (items.length === 0) {
                printContent += '<div class="center small">No transactions found</div>';
            } else {
                items.forEach(it => {
                    const title = it.querySelector('.txn-title')?.textContent.trim() || '';
                    const subContent = it.querySelector('.txn-sub')?.textContent.trim() || '';
                    const amtText = it.querySelector('.txn-amount')?.textContent.trim() || '';
                    
                    // Extract date from sub content - look for date pattern
                    let dateStr = '';
                    let timeStr = '';
                    
                    // Try to extract date from the transaction sub text
                    const dateTimeMatch = subContent.match(/(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})/);
                    if (dateTimeMatch) {
                        dateStr = dateTimeMatch[1];
                        timeStr = dateTimeMatch[2];
                    } else {
                        // Fallback - try to get just date
                        const dateMatch = subContent.match(/(\d{4}-\d{2}-\d{2})/);
                        if (dateMatch) {
                            dateStr = dateMatch[1];
                        } else {
                            dateStr = 'N/A';
                        }
                    }
                    
                    // Extract reference from sub content
                    const refMatch = subContent.match(/Ref:\s*([^\s•]+)/);
                    const refStr = refMatch ? refMatch[1] : '';
                    
                    // Extract payment method from title
                    const method = title.includes(' - ') ? title.split(' - ')[1].trim() : title.replace('Payment Received - ', '').replace('Payment Made - ', '');
                    
                    printContent += `
                        <div class="row"><span class="small">${dateStr}</span><span class="bold">${amtText}</span></div>
                        <div class="row"><span class="small">${method}</span><span class="small">${timeStr}</span></div>
                        ${refStr ? `<div class="row"><span class="small">Ref: ${refStr}</span><span></span></div>` : ''}
                        <div style="margin: 2px 0;"></div>
                    `;
                });
            }
            
            printContent += `
                <div class="dash"></div>
                <div class="center small">*** END OF STATEMENT ***</div>
                <div class="center small">Rice Business Management</div>
            `;

            const w = window.open('', '_blank', 'width=320,height=600');
            w.document.write(printContent);
            w.document.close();
            w.focus();
            setTimeout(() => { w.print(); w.close(); }, 250);
        }
    </script>
</body>
</html>
