<?php
session_start();
include("db_connect.php");
include 'require_cash_session.php'; // ensures there is an OPEN cash session

if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

$cashier       = $_SESSION['username'] ?? 'unknown';
$cashSessionId = $_SESSION['cash_session_id'] ?? null;

if (!$cashSessionId) {
    // Extra safety – if for any reason the session ID is missing
    header("Location: open_cash_session.php");
    exit();
}

$page_title = "Close Cash Session";
$active     = 'cash_session'; // optional nav highlight
$message    = "";

/* -------------------------------------------------
   1. LOAD CASH SESSION INFO
   Adjust column names to match your cash_sessions table
-------------------------------------------------- */

// cash_sessions expected columns we will use:
//  id, cashier, opening_float, opened_at, closing_cash_expected,
//  closing_cash_counted, variance, closing_note, closed_at, is_open

$sessionStmt = $conn->prepare("
    SELECT id, cashier, opening_float, opened_at
    FROM cash_sessions
    WHERE id = ?
    LIMIT 1
");
$sessionStmt->bind_param("i", $cashSessionId);
$sessionStmt->execute();
$sessionRes   = $sessionStmt->get_result();
$cashSession  = $sessionRes->fetch_assoc();
$sessionStmt->close();

if (!$cashSession) {
    // If somehow the row is missing, force user to open a new one
    $_SESSION['cash_session_id'] = null;
    header("Location: open_cash_session.php");
    exit();
}

// We’ll use the date of the session for daily expenses filter
$sessionDate = date('Y-m-d', strtotime($cashSession['opened_at']));

/* -------------------------------------------------
   2. LOAD PAYMENT SUMMARY FOR THIS SESSION (NORMAL SALES)
   FROM payments table (linked via cash_session_id)
-------------------------------------------------- */

$totalsStmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(amount_due), 0)               AS total_due,
        COALESCE(SUM(paid_at), 0)                  AS total_paid,
        COALESCE(SUM(change_amount), 0)            AS total_change,
        COALESCE(SUM(CASE WHEN payment_method = 'cash'  THEN paid_at END), 0) AS total_cash,
        COALESCE(SUM(CASE WHEN payment_method = 'mpesa' THEN paid_at END), 0) AS total_mpesa,
        COALESCE(SUM(CASE WHEN payment_method = 'bank'  THEN paid_at END), 0) AS total_bank,
        COUNT(DISTINCT receipt_id) AS receipt_count
    FROM payments
    WHERE cash_session_id = ?
");
$totalsStmt->bind_param("i", $cashSessionId);
$totalsStmt->execute();
$totals    = $totalsStmt->get_result()->fetch_assoc();
$totalsStmt->close();

/* -------------------------------------------------
   2a. LOAD CREDIT PAYMENT SUMMARY FOR THIS SESSION
   FROM debt_payments table (credit repayments)
   Only rows tied to this cash_session_id are included.
-------------------------------------------------- */

$dpStmt = $conn->prepare("
    SELECT
        COALESCE(SUM(CASE WHEN payment_method = 'cash'  THEN amount_paid END), 0) AS dp_cash,
        COALESCE(SUM(CASE WHEN payment_method = 'mpesa' THEN amount_paid END), 0) AS dp_mpesa,
        COALESCE(SUM(CASE WHEN payment_method = 'bank'  THEN amount_paid END), 0) AS dp_bank,
        COUNT(DISTINCT receipt_id) AS dp_receipts
    FROM debt_payments
    WHERE cash_session_id = ?
");
$dpStmt->bind_param("i", $cashSessionId);
$dpStmt->execute();
$dpTotals = $dpStmt->get_result()->fetch_assoc();
$dpStmt->close();

/* -------------------------------------------------
   2b. LOAD EXPENSES SUMMARY FOR THIS SESSION/DAY
   FROM expenses table (by date + cashier)
-------------------------------------------------- */

$expensesStmt = $conn->prepare("
    SELECT
        COALESCE(SUM(amount), 0)                                                     AS total_expenses,
        COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN amount END), 0)          AS cash_expenses,
        COALESCE(SUM(CASE WHEN payment_method = 'mpesa' THEN amount END), 0)         AS mpesa_expenses,
        COALESCE(SUM(CASE WHEN payment_method = 'bank' THEN amount END), 0)          AS bank_expenses
    FROM expenses
    WHERE DATE(expense_date) = ?
      AND cashier = ?
");
$expensesStmt->bind_param("ss", $sessionDate, $cashier);
$expensesStmt->execute();
$expenseTotals = $expensesStmt->get_result()->fetch_assoc();
$expensesStmt->close();

/* -------------------------------------------------
   2c. COMBINE NORMAL PAYMENTS + CREDIT PAYMENTS
-------------------------------------------------- */

$openingFloat = (float)$cashSession['opening_float'];

// Normal payments
$normalCash      = (float)$totals['total_cash'];
$normalMpesa     = (float)$totals['total_mpesa'];
$normalBank      = (float)$totals['total_bank'];
$totalChange     = (float)$totals['total_change'];
$normalReceipts  = (int)$totals['receipt_count'];

// Credit payments
$dpCash     = (float)$dpTotals['dp_cash'];
$dpMpesa    = (float)$dpTotals['dp_mpesa'];
$dpBank     = (float)$dpTotals['dp_bank'];
$dpReceipts = (int)$dpTotals['dp_receipts'];

// Combined (for display)
$totalCash    = $normalCash  + $dpCash;
$totalMpesa   = $normalMpesa + $dpMpesa;
$totalBank    = $normalBank  + $dpBank;
$receiptCount = $normalReceipts + $dpReceipts;

// Expenses
$totalExpenses = (float)$expenseTotals['total_expenses'];
$cashExpenses  = (float)$expenseTotals['cash_expenses'];
$mpesaExpenses = (float)$expenseTotals['mpesa_expenses'];
$bankExpenses  = (float)$expenseTotals['bank_expenses'];

// 🔢 Expected cash in drawer:
// = opening float + ALL cash received (normal + credit) - change given - cash expenses
$expectedCashDrawer = $openingFloat + $totalCash - $totalChange - $cashExpenses;
if ($expectedCashDrawer < 0) {
    $expectedCashDrawer = 0.0; // just in case
}

/* -------------------------------------------------
   3. HANDLE SUBMIT – CLOSE SESSION
   After this, next time the cashier must open a NEW session,
   and all future pages must filter by the new cash_session_id,
   so they start "fresh" with no previous transactions.
-------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_session'])) {

    $counted_cash = isset($_POST['counted_cash']) ? (float)$_POST['counted_cash'] : 0.0;
    $closing_note = trim($_POST['closing_note'] ?? '');

    if ($counted_cash <= 0) {
        $message = "❌ Please enter the counted cash in the drawer.";
    } else {

        // Recompute NORMAL payments (server-side safety)
        $totalsStmt2 = $conn->prepare("
            SELECT 
                COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN paid_at END), 0) AS total_cash,
                COALESCE(SUM(change_amount), 0)                                       AS total_change
            FROM payments
            WHERE cash_session_id = ?
        ");
        $totalsStmt2->bind_param("i", $cashSessionId);
        $totalsStmt2->execute();
        $totals2 = $totalsStmt2->get_result()->fetch_assoc();
        $totalsStmt2->close();

        $normalCash2  = (float)$totals2['total_cash'];
        $totalChange2 = (float)$totals2['total_change'];

        // Recompute CREDIT payments (cash only) for this session
        $dpStmt2 = $conn->prepare("
            SELECT
                COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN amount_paid END), 0) AS dp_cash
            FROM debt_payments
            WHERE cash_session_id = ?
        ");
        $dpStmt2->bind_param("i", $cashSessionId);
        $dpStmt2->execute();
        $dp2 = $dpStmt2->get_result()->fetch_assoc();
        $dpStmt2->close();

        $dpCash2 = (float)$dp2['dp_cash'];

        // Recompute cash expenses for this session date + cashier
        $expensesStmt2 = $conn->prepare("
            SELECT
                COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN amount END), 0) AS cash_expenses
            FROM expenses
            WHERE DATE(expense_date) = ?
              AND cashier = ?
        ");
        $expensesStmt2->bind_param("ss", $sessionDate, $cashier);
        $expensesStmt2->execute();
        $exp2 = $expensesStmt2->get_result()->fetch_assoc();
        $expensesStmt2->close();

        $cashExpenses2 = (float)$exp2['cash_expenses'];

        // Combine normal + credit cash
        $totalCashAll = $normalCash2 + $dpCash2;

        $expectedCash = $openingFloat + $totalCashAll - $totalChange2 - $cashExpenses2;
        if ($expectedCash < 0) {
            $expectedCash = 0.0;
        }

        $variance = $counted_cash - $expectedCash; // positive = extra; negative = shortage

        // ✅ UPDATE CASH SESSION AS CLOSED
        $updateStmt = $conn->prepare("
            UPDATE cash_sessions
            SET 
                closing_cash_expected = ?,
                closing_cash_counted  = ?,
                variance              = ?,
                closing_note          = ?,
                closed_at             = NOW(),
                is_open               = 0
            WHERE id = ?
        ");
        // dddsi = 3 doubles, 1 string, 1 int
        $updateStmt->bind_param(
            "dddsi",
            $expectedCash,
            $counted_cash,
            $variance,
            $closing_note,
            $cashSessionId
        );
        $updateStmt->execute();
        $updateStmt->close();

        // Remove session from PHP so user must open a new one next time
        unset($_SESSION['cash_session_id']);

        // Optional: clear any cart still in memory
        unset($_SESSION['cart'], $_SESSION['receipt_id']);

        $_SESSION['flash_message'] = "✔ Cash session closed successfully.";
        header("Location: cashier_dashboard.php");
        exit();
    }
}

// Helper for safe echo
function h($v) { return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        .pos-wrapper {
            max-width: 1300px;
            margin: 0 auto;
            width: 100%;
        }

        .pos-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.10), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 22px 24px 26px;
            box-shadow: 0 18px 40px rgba(0, 0, 0, 0.55);
            border: 1px solid var(--cash-border-soft);
        }

        html[data-theme="light"] .pos-card {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.12), transparent 55%),
                #ffffff;
            box-shadow: 0 10px 22px rgba(15,23,42,0.12);
            border-color: #dbeafe;
        }

        .pos-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 18px;
            gap: 10px;
        }

        .pos-header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .pos-header p {
            font-size: 13px;
            color: var(--cash-text-muted);
            margin-top: 2px;
        }

        html[data-theme="light"] .pos-header p {
            color: #475569;
        }

        .session-pill {
            padding: 6px 14px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.7);
            background:
                radial-gradient(circle at 0% 0%, rgba(34,211,238,0.24), transparent 60%),
                rgba(15,23,42,0.96);
            font-size: 12px;
            color: var(--cash-accent-alt);
            white-space: nowrap;
        }

        html[data-theme="light"] .session-pill {
            background:
                radial-gradient(circle at 0% 0%, rgba(56,189,248,0.18), transparent 60%),
                #eff6ff;
            color: #0369a1;
        }

        .metric-strip {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 10px 0 16px;
        }

        .metric-chip {
            flex: 0 0 auto;
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(1,22,61,0.75);
            border: 1px solid rgba(130,238,253,0.8);
            font-size: 12px;
        }

        html[data-theme="light"] .metric-chip {
            background: #eff6ff;
            border-color: #bae6fd;
            color: #0f172a;
        }

        .metric-label {
            color: #82EEFD;
            font-weight: 500;
            margin-right: 6px;
        }

        html[data-theme="light"] .metric-label {
            color: #0369a1;
        }

        .metric-value {
            font-weight: 600;
        }

        .close-form {
            margin-top: 10px;
            display: grid;
            grid-template-columns: minmax(0, 1fr);
            gap: 10px;
        }

        .field-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
            font-size: 13px;
        }

        .field-group label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            opacity: 0.85;
        }

        .field-group input[type="number"],
        .field-group textarea {
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.6);
            background: #001B3A;
            color: #ffffff;
            font-size: 13px;
        }

        html[data-theme="light"] .field-group input[type="number"],
        html[data-theme="light"] .field-group textarea {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .field-group textarea {
            min-height: 80px;
            resize: vertical;
        }

        .btn-primary-submit {
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            border-radius: 10px;
            border: none;
            padding: 10px 18px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 10px 26px rgba(0,0,0,0.55);
        }

        .btn-primary-submit:hover {
            filter: brightness(1.06);
        }

        .pos-actions {
            margin-top: 16px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }

        .back-link {
            font-size: 13px;
            color: var(--cash-accent-alt);
            text-decoration: none;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        .pos-message {
            margin-bottom: 10px;
            border-radius: 10px;
            padding: 10px 12px;
            font-size: 13px;
        }

        .pos-message.error {
            background: rgba(220,38,38,0.12);
            border-left: 3px solid #ef4444;
            color: #fecaca;
        }

        html[data-theme="light"] .pos-message.error {
            background: #fee2e2;
            color: #b91c1c;
        }
    </style>
</head>
<body>

<div class="cashier-shell">

    <?php include 'cashier_sidebar.php'; ?>

    <main class="cashier-main">
        <div class="pos-wrapper">

            <!-- TOP BAR -->
            <div class="cashier-topbar">
                <div class="cashier-topbar-left">
                    <h1>Close cash session</h1>
                    <small>Review totals for this drawer and submit the closing balance.</small>
                </div>
                <div class="cashier-topbar-right">
                    <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                        <span class="icon">🌓</span>
                        <span class="label">Theme</span>
                    </button>
                    <button class="cashier-toggle" type="button" onclick="toggleCashierSidebar()">☰</button>
                </div>
            </div>

            <!-- MAIN CARD -->
            <section class="pos-card">
                <div class="pos-header">
                    <div>
                        <h2>Session summary</h2>
                        <p>
                            Cashier: <?= h($cashSession['cashier']); ?>
                            · Opened at: <?= h($cashSession['opened_at']); ?>
                            · Date: <?= h($sessionDate); ?>
                        </p>
                    </div>
                    <span class="session-pill">
                        Session ID · <?= (int)$cashSession['id']; ?>
                    </span>
                </div>

                <?php if (!empty($message)) : ?>
                    <div class="pos-message error">
                        <?= $message ?>
                    </div>
                <?php endif; ?>

                <div class="metric-strip">
                    <div class="metric-chip">
                        <span class="metric-label">Opening float</span>
                        <span class="metric-value">KES <?= number_format($openingFloat, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Receipts</span>
                        <span class="metric-value"><?= $receiptCount; ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Cash received</span>
                        <span class="metric-value">KES <?= number_format($totalCash, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">M-Pesa received</span>
                        <span class="metric-value">KES <?= number_format($totalMpesa, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Bank received</span>
                        <span class="metric-value">KES <?= number_format($totalBank, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Change given</span>
                        <span class="metric-value">KES <?= number_format($totalChange, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Expenses (cash)</span>
                        <span class="metric-value">KES <?= number_format($cashExpenses, 2); ?></span>
                    </div>
                    <div class="metric-chip">
                        <span class="metric-label">Expected cash</span>
                        <span class="metric-value">KES <?= number_format($expectedCashDrawer, 2); ?></span>
                    </div>
                </div>

                <form method="post" class="close-form">
                    <div class="field-group">
                        <label for="counted_cash">Counted cash in drawer (KES)</label>
                        <input
                            type="number"
                            name="counted_cash"
                            id="counted_cash"
                            step="0.01"
                            min="0"
                            placeholder="Enter the actual cash you counted"
                            required
                        >
                    </div>

                    <div class="field-group">
                        <label for="closing_note">Notes (optional)</label>
                        <textarea
                            name="closing_note"
                            id="closing_note"
                            placeholder="Eg. Shift ended, handed over to next cashier, shortages explained, etc."
                        ></textarea>
                    </div>

                    <div class="pos-actions">
                        <button
                            type="submit"
                            name="close_session"
                            class="btn-primary-submit"
                            onclick="return confirm('Close this cash session? You will need to open a new one for further sales.');"
                        >
                            Close cash session
                        </button>
                        <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
                    </div>
                </form>
            </section>

        </div>
    </main>
</div>

<?php include 'footer.php'; ?>

</body>
</html>
