<?php
session_start();
include("db_connect.php");

// Only cashiers (or adjust as needed)
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

$cashier    = $_SESSION['username'];
$page_title = "Open Cash Drawer";
$active     = 'cash_session'; // custom active key for nav highlight
$message    = "";

/**
 * IMPORTANT:
 * We now use `is_open` to determine if a session is active.
 * close_cash_session.php sets: is_open = 0, closed_at = NOW()
 */

// Check if there is already an OPEN session for this cashier
$existing_open = null;
$check_sql = "
    SELECT id
    FROM cash_sessions 
    WHERE cashier = ? AND is_open = 1
    ORDER BY id DESC
    LIMIT 1
";
if ($stmt = $conn->prepare($check_sql)) {
    $stmt->bind_param("s", $cashier);
    $stmt->execute();
    $stmt->bind_result($open_id);
    if ($stmt->fetch()) {
        $existing_open = (int)$open_id;
    }
    $stmt->close();
}

// If a session is already open, store it in session
if ($existing_open && !isset($_SESSION['cash_session_id'])) {
    $_SESSION['cash_session_id'] = $existing_open;
    // Optional redirect:
//  header("Location: scan_sales.php");
//  exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['opening_float'])) {
    $opening_float = (float) $_POST['opening_float'];

    if ($opening_float < 0) {
        $message = "❌ Opening float cannot be negative.";
    } else {
        // If there is already an open session, don't create another
        if ($existing_open) {
            $_SESSION['cash_session_id'] = $existing_open;
            header("Location: scan_sales.php");
            exit();
        }

        // Insert new cash session row using is_open flag
        $sql = "
            INSERT INTO cash_sessions
                (cashier, opening_float, opened_at, is_open)
            VALUES
                (?, ?, NOW(), 1)
        ";

        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("sd", $cashier, $opening_float);
            if ($stmt->execute()) {
                $new_id = $stmt->insert_id;
                $_SESSION['cash_session_id'] = $new_id;

                // After opening the drawer, send cashier to POS
                header("Location: scan_sales.php");
                exit();
            } else {
                $message = "❌ Failed to open cash drawer. Please try again.";
            }
            $stmt->close();
        } else {
            $message = "❌ Database error when preparing statement.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        :root {
            --cash-accent-main: var(--cash-accent-main, #22d3ee);
            --cash-accent-soft: var(--cash-accent-soft, #7dd3fc);
        }

        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

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

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

        .pos-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.12), 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.10), transparent 55%),
                #ffffff;
            box-shadow: 0 10px 22px rgba(15,23,42,0.12);
            border-color: #dbeafe;
        }

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

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

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

        .pos-message {
            margin-top: 12px;
            margin-bottom: 14px;
            border-radius: 10px;
            padding: 9px 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;
        }

        .form-group {
            margin-top: 18px;
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .form-group label {
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            opacity: 0.9;
        }

        .form-group input[type="number"] {
            padding: 10px 12px;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.55);
            background: #001B3A;
            color: #ffffff;
            font-size: 14px;
        }

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

        .form-group input[type="number"]:focus {
            outline: none;
            border-color: #22d3ee;
            box-shadow: 0 0 0 1px rgba(34,211,238,0.55);
        }

        .hint {
            font-size: 12px;
            color: var(--cash-text-muted);
        }

        html[data-theme="light"] .hint {
            color: #64748b;
        }

        .pos-actions {
            margin-top: 18px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

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

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

        .btn-secondary {
            background: rgba(15,23,42,0.9);
            color: #e5e7eb;
            border-radius: 10px;
            border: 1px solid rgba(148,163,184,0.7);
            padding: 10px 16px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
        }

        .btn-secondary:hover {
            background: rgba(15,23,42,1);
        }

        html[data-theme="light"] .btn-secondary {
            background: #f3f4f6;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        html[data-theme="light"] .btn-secondary:hover {
            background: #e5e7eb;
        }

        .back-link-inline {
            font-size: 13px;
            color: var(--cash-accent-soft);
            text-decoration: none;
            margin-top: 10px;
            display: inline-block;
        }

        .back-link-inline:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include 'cashier_sidebar.php'; ?>

    <main class="cashier-main">
        <div class="pos-wrapper">
            <div class="cashier-topbar">
                <div class="cashier-topbar-left">
                    <h1><?= htmlspecialchars($page_title); ?></h1>
                    <small>Start your shift by declaring the cash placed in the drawer.</small>
                </div>

                <div class="cashier-topbar-right">
                    <nav class="cashier-topnav">
                        <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                        <a href="scan_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                        <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                        <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Debts</a>
                    </nav>

                    <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>

            <section class="pos-card">
                <div class="pos-header">
                    <h2>Open cash drawer</h2>
                    <p>Enter the float amount (starting cash) in your till for this shift.</p>
                </div>

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

                <form method="post" autocomplete="off">
                    <div class="form-group">
                        <label for="opening_float">Opening float (KES)</label>
                        <input
                            type="number"
                            name="opening_float"
                            id="opening_float"
                            min="0"
                            step="0.01"
                            required
                            autofocus
                        >
                        <div class="hint">
                            Example: 5000.00. This is the cash you physically put into the drawer at the start of your shift.
                        </div>
                    </div>

                    <div class="pos-actions">
                        <button type="submit" class="btn-primary">Open drawer &amp; start shift</button>
                        <a href="cashier_dashboard.php" class="btn-secondary">Cancel</a>
                    </div>

                    <a href="cashier_dashboard.php" class="back-link-inline">← Back to dashboard</a>
                </form>
            </section>
        </div>
    </main>
</div>

<?php include 'footer.php'; ?>
</body>
</html>
