<?php
require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

$business_id = $current_business['business_id'];
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

// Summary of Sales by Term
$sales_summary = all_rows("
    SELECT payment_terms, SUM(grand_total) as total 
    FROM sales 
    WHERE business_id = ? AND sale_date BETWEEN ? AND ? 
    GROUP BY payment_terms", [$business_id, $from, $to]);

$sale_totals = ['Cash' => 0, 'Credit' => 0];
foreach($sales_summary as $s) {
    if($s['payment_terms'] == 'Cash') $sale_totals['Cash'] = (float)$s['total'];
    if($s['payment_terms'] == 'Credit') $sale_totals['Credit'] = (float)$s['total'];
}

// Summary of Purchases by Term
$purchase_summary = all_rows("
    SELECT payment_terms, SUM(grand_total) as total 
    FROM purchases 
    WHERE business_id = ? AND purchase_date BETWEEN ? AND ? 
    GROUP BY payment_terms", [$business_id, $from, $to]);

$pur_totals = ['Cash' => 0, 'Credit' => 0];
foreach($purchase_summary as $p) {
    if($p['payment_terms'] == 'Cash') $pur_totals['Cash'] = (float)$p['total'];
    if($p['payment_terms'] == 'Credit') $pur_totals['Credit'] = (float)$p['total'];
}

// Combined History (Includes ID for linking)
$history = all_rows("
    (SELECT 'SALE' as type, s.id, sale_date as date, bill_no, payment_terms, grand_total as amount, a.name as party_name 
      FROM sales s LEFT JOIN accounts a ON s.party_id = a.id 
      WHERE s.business_id = ? AND s.sale_date BETWEEN ? AND ?)
    UNION ALL
    (SELECT 'PURCHASE' as type, p.id, purchase_date as date, bill_no, payment_terms, grand_total as amount, a.name as party_name 
      FROM purchases p LEFT JOIN accounts a ON p.party_id = a.id 
      WHERE p.business_id = ? AND p.purchase_date BETWEEN ? AND ?)
    ORDER BY date DESC", [$business_id, $from, $to, $business_id, $from, $to]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Cash & Credit Report</title>
    <style>
        body { 
            background-image: url("<?= BASE_URL ?>/public/grocery.png");
            background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-position: center;
            background-color: #f4f6f9; font-size: 14px;
        }
        .card { border-radius: 8px; padding: 15px; border:none; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .table th { background: #6f42c1; color: white; font-weight: 500; }
        .stat-card { text-align: center; padding: 20px; border-radius: 12px; }
        .bg-cash { background-color: #d1e7dd; color: #0f5132; }
        .bg-credit { background-color: #f8d7da; color: #842029; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <h4 class="mb-3">Cash & Credit Sales Report</h4>

    <form class="row g-2 align-items-end mb-4">
        <input type="hidden" name="r" value="reports/cash_credit">
        <div class="col-auto">
            <label class="form-label">From</label>
            <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
        </div>
        <div class="col-auto">
            <label class="form-label">To</label>
            <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
        </div>
        <div class="col-auto">
            <button class="btn btn-primary">Filter</button>
        </div>
    </form>

    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="stat-card bg-cash">
                <h4>₹ <?= number_format($sale_totals['Cash'], 2) ?></h4>
                <p class="mb-0 fw-bold">CASH SALES</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card bg-credit">
                <h4>₹ <?= number_format($sale_totals['Credit'], 2) ?></h4>
                <p class="mb-0 fw-bold">CREDIT SALES</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card bg-light border border-success text-success">
                <h4>₹ <?= number_format($pur_totals['Cash'], 2) ?></h4>
                <p class="mb-0 fw-bold text-dark">CASH PURCHASES</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card bg-light border border-danger text-danger">
                <h4>₹ <?= number_format($pur_totals['Credit'], 2) ?></h4>
                <p class="mb-0 fw-bold text-dark">CREDIT PURCHASES</p>
            </div>
        </div>
    </div>

    <div class="card p-0">
        <div class="card-header bg-white">
            <h5 class="mb-0">Transaction History (Sales & Purchases)</h5>
        </div>
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Ref #</th>
                    <th>Party</th>
                    <th>Terms</th>
                    <th class="text-end">Amount</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($history as $h): ?>
                <tr>
                    <td><?= date('d-m-Y', strtotime($h['date'])) ?></td>
                    <td>
                        <small class="badge <?= $h['type'] == 'SALE' ? 'bg-info' : 'bg-warning text-dark' ?>">
                            <?= $h['type'] ?>
                        </small>
                    </td>
                    <td><?= e($h['bill_no']) ?></td>
                    <td><?= e($h['party_name'] ?: 'Retail') ?></td>
                    <td>
                        <span class="badge <?= $h['payment_terms'] == 'Cash' ? 'bg-success' : 'bg-danger' ?>">
                            <?= e($h['payment_terms']) ?>
                        </span>
                    </td>
                    <td class="text-end fw-bold">₹ <?= number_format($h['amount'], 2) ?></td>
                    
                    <td class="text-center">
                        <?php if($h['type'] === 'SALE'): ?>
                            <a href="index.php?r=sale&id=<?= $h['id'] ?>" class="btn btn-sm btn-outline-primary py-0">
                                View
                            </a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($history)): ?>
                    <tr><td colspan="7" class="text-center py-4">No transactions found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>