<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'POS Shifts';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('shift_flash')) {
    function shift_flash(string $type, string $message): void {
        $_SESSION['pos_shift_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('shift_get_flash')) {
    function shift_get_flash(): array {
        $items = $_SESSION['pos_shift_flash'] ?? [];
        unset($_SESSION['pos_shift_flash']);
        return $items;
    }
}
if (!function_exists('shift_table_exists')) {
    function shift_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('shift_column_exists')) {
    function shift_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('shift_add_col')) {
    function shift_add_col(PDO $pdo, string $table, string $column, string $sql): void {
        if (!shift_column_exists($pdo, $table, $column)) {
            $pdo->exec($sql);
        }
    }
}
if (!function_exists('shift_user_name_expr')) {
    function shift_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!shift_table_exists($pdo, 'users')) return "NULL";
        if (shift_column_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (shift_column_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (shift_column_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (shift_column_exists($pdo, 'users', 'email')) return "{$alias}.email";
        return "CONCAT('User #', {$alias}.id)";
    }
}
if (!function_exists('shift_no')) {
    function shift_no(PDO $pdo): string {
        $prefix = 'SHIFT-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM pos_shifts WHERE shift_no LIKE :p");
        $stmt->execute([':p' => $prefix . '%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('shift_calc_sales')) {
    function shift_calc_sales(PDO $pdo, int $shiftId): array {
        $stmt = $pdo->prepare("SELECT * FROM pos_shifts WHERE id=:id LIMIT 1");
        $stmt->execute([':id' => $shiftId]);
        $shift = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$shift) throw new RuntimeException('Shift not found.');

        $end = !empty($shift['closed_at']) ? $shift['closed_at'] : date('Y-m-d H:i:s');

        $stmt = $pdo->prepare("
            SELECT
                COUNT(*) AS receipts,
                COALESCE(SUM(CASE WHEN status <> 'void' THEN total_amount ELSE 0 END),0) AS total_sales,
                COALESCE(SUM(CASE WHEN status = 'void' THEN total_amount ELSE 0 END),0) AS void_sales,
                COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='cash' THEN total_amount ELSE 0 END),0) AS cash_sales,
                COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='card' THEN total_amount ELSE 0 END),0) AS card_sales,
                COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='transfer' THEN total_amount ELSE 0 END),0) AS transfer_sales,
                COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='room_charge' THEN total_amount ELSE 0 END),0) AS room_charge_sales,
                COALESCE(SUM(CASE WHEN status <> 'void' AND payment_method='complimentary' THEN total_amount ELSE 0 END),0) AS complimentary_sales
            FROM pos_orders
            WHERE store_id = :store_id
              AND created_at BETWEEN :opened_at AND :closed_at
        ");
        $stmt->execute([
            ':store_id' => (int)$shift['store_id'],
            ':opened_at' => $shift['opened_at'],
            ':closed_at' => $end,
        ]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $openingFloat = (float)($shift['opening_float'] ?? 0);
        $cashSales = (float)($row['cash_sales'] ?? 0);
        $cashDrops = (float)($shift['cash_drops'] ?? 0);
        $pettyCashOut = (float)($shift['petty_cash_out'] ?? 0);
        $expectedCash = $openingFloat + $cashSales - $cashDrops - $pettyCashOut;

        return [
            'receipts' => (int)($row['receipts'] ?? 0),
            'total_sales' => (float)($row['total_sales'] ?? 0),
            'void_sales' => (float)($row['void_sales'] ?? 0),
            'cash_sales' => $cashSales,
            'card_sales' => (float)($row['card_sales'] ?? 0),
            'transfer_sales' => (float)($row['transfer_sales'] ?? 0),
            'room_charge_sales' => (float)($row['room_charge_sales'] ?? 0),
            'complimentary_sales' => (float)($row['complimentary_sales'] ?? 0),
            'expected_cash' => $expectedCash,
        ];
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        pos_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        order_id INT UNSIGNED NULL,
        folio_id INT UNSIGNED NULL,
        guest_name VARCHAR(180) NULL,
        room_label VARCHAR(80) NULL,
        sale_type ENUM('cash','card','transfer','room_charge','complimentary','void') NOT NULL DEFAULT 'cash',
        payment_method VARCHAR(40) NULL,
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        discount_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        status ENUM('open','paid','charged_to_room','void') NOT NULL DEFAULT 'open',
        notes TEXT NULL,
        void_reason TEXT NULL,
        voided_at DATETIME NULL,
        voided_by INT UNSIGNED NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_no (pos_no),
        INDEX idx_pos_store (store_id),
        INDEX idx_pos_status (status),
        INDEX idx_pos_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_shifts (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        shift_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        cashier_id INT UNSIGNED NULL,
        opened_by INT UNSIGNED NULL,
        closed_by INT UNSIGNED NULL,
        opened_at DATETIME NOT NULL,
        closed_at DATETIME NULL,
        opening_float DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        cash_drops DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        petty_cash_out DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        expected_cash DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        counted_cash DECIMAL(14,2) NULL,
        variance DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        cash_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        card_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        transfer_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        room_charge_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        complimentary_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        void_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        receipt_count INT UNSIGNED NOT NULL DEFAULT 0,
        status ENUM('open','closed') NOT NULL DEFAULT 'open',
        opening_notes TEXT NULL,
        closing_notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_shift_no (shift_no),
        INDEX idx_pos_shift_store (store_id),
        INDEX idx_pos_shift_status (status),
        INDEX idx_pos_shift_dates (opened_at, closed_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_shift_events (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        shift_id BIGINT UNSIGNED NOT NULL,
        event_type ENUM('open','cash_drop','petty_cash_out','close','reopen','note') NOT NULL,
        amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_shift_events_shift (shift_id),
        INDEX idx_shift_events_type (event_type)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    foreach ([
        'cash_drops' => "ALTER TABLE pos_shifts ADD COLUMN cash_drops DECIMAL(14,2) NOT NULL DEFAULT 0.00 AFTER opening_float",
        'petty_cash_out' => "ALTER TABLE pos_shifts ADD COLUMN petty_cash_out DECIMAL(14,2) NOT NULL DEFAULT 0.00 AFTER cash_drops",
        'expected_cash' => "ALTER TABLE pos_shifts ADD COLUMN expected_cash DECIMAL(14,2) NOT NULL DEFAULT 0.00 AFTER petty_cash_out",
        'counted_cash' => "ALTER TABLE pos_shifts ADD COLUMN counted_cash DECIMAL(14,2) NULL AFTER expected_cash",
        'variance' => "ALTER TABLE pos_shifts ADD COLUMN variance DECIMAL(14,2) NOT NULL DEFAULT 0.00 AFTER counted_cash",
    ] as $col => $sql) {
        shift_add_col($pdo, 'pos_shifts', $col, $sql);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare POS shift tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');
        $userId = (int)($_SESSION['user_id'] ?? 0);

        if ($action === 'open_shift') {
            $storeId = (int)($_POST['store_id'] ?? 0);
            $openingFloat = (float)($_POST['opening_float'] ?? 0);
            $notes = trim((string)($_POST['opening_notes'] ?? ''));

            if ($storeId <= 0) throw new RuntimeException('Please select POS store.');

            $stmt = $pdo->prepare("SELECT * FROM store_locations WHERE id=:id AND is_active=1 LIMIT 1");
            $stmt->execute([':id' => $storeId]);
            $store = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$store) throw new RuntimeException('Store location not found.');
            if ((int)$store['is_pos_location'] !== 1) throw new RuntimeException('This store is not enabled for POS.');

            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM pos_shifts
                WHERE store_id=:store_id
                  AND status='open'
            ");
            $stmt->execute([':store_id' => $storeId]);
            if ((int)$stmt->fetchColumn() > 0) {
                throw new RuntimeException('There is already an open shift for this store. Close it first.');
            }

            $pdo->beginTransaction();

            $shiftNo = shift_no($pdo);
            $stmt = $pdo->prepare("
                INSERT INTO pos_shifts
                (shift_no, store_id, cashier_id, opened_by, opened_at, opening_float, expected_cash, status, opening_notes)
                VALUES
                (:shift_no, :store_id, :cashier_id, :opened_by, NOW(), :opening_float, :expected_cash, 'open', :opening_notes)
            ");
            $stmt->execute([
                ':shift_no' => $shiftNo,
                ':store_id' => $storeId,
                ':cashier_id' => $userId ?: null,
                ':opened_by' => $userId ?: null,
                ':opening_float' => $openingFloat,
                ':expected_cash' => $openingFloat,
                ':opening_notes' => $notes ?: null,
            ]);

            $shiftId = (int)$pdo->lastInsertId();

            $stmt = $pdo->prepare("
                INSERT INTO pos_shift_events
                (shift_id, event_type, amount, notes, created_by)
                VALUES
                (:shift_id, 'open', :amount, :notes, :created_by)
            ");
            $stmt->execute([
                ':shift_id' => $shiftId,
                ':amount' => $openingFloat,
                ':notes' => $notes ?: 'Shift opened',
                ':created_by' => $userId ?: null,
            ]);

            $pdo->commit();

            shift_flash('success', 'Shift opened successfully: ' . $shiftNo);
            header('Location: pos_shifts.php?view_id=' . $shiftId);
            exit;
        }

        if ($action === 'cash_drop' || $action === 'petty_cash_out') {
            $shiftId = (int)($_POST['shift_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($shiftId <= 0) throw new RuntimeException('Invalid shift.');
            if ($amount <= 0) throw new RuntimeException('Amount must be greater than zero.');

            $stmt = $pdo->prepare("SELECT * FROM pos_shifts WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $shiftId]);
            $shift = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$shift) throw new RuntimeException('Shift not found.');
            if ($shift['status'] !== 'open') throw new RuntimeException('Only open shifts can be updated.');

            $field = $action === 'cash_drop' ? 'cash_drops' : 'petty_cash_out';

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("UPDATE pos_shifts SET {$field} = COALESCE({$field},0) + :amount WHERE id=:id");
            $stmt->execute([':amount' => $amount, ':id' => $shiftId]);

            $stmt = $pdo->prepare("
                INSERT INTO pos_shift_events
                (shift_id, event_type, amount, notes, created_by)
                VALUES
                (:shift_id, :event_type, :amount, :notes, :created_by)
            ");
            $stmt->execute([
                ':shift_id' => $shiftId,
                ':event_type' => $action,
                ':amount' => $amount,
                ':notes' => $notes ?: null,
                ':created_by' => $userId ?: null,
            ]);

            $pdo->commit();

            shift_flash('success', $action === 'cash_drop' ? 'Cash drop recorded.' : 'Petty cash out recorded.');
            header('Location: pos_shifts.php?view_id=' . $shiftId);
            exit;
        }

        if ($action === 'close_shift') {
            $shiftId = (int)($_POST['shift_id'] ?? 0);
            $countedCash = (float)($_POST['counted_cash'] ?? 0);
            $notes = trim((string)($_POST['closing_notes'] ?? ''));

            if ($shiftId <= 0) throw new RuntimeException('Invalid shift.');
            if ($countedCash < 0) throw new RuntimeException('Counted cash cannot be negative.');

            $stmt = $pdo->prepare("SELECT * FROM pos_shifts WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $shiftId]);
            $shift = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$shift) throw new RuntimeException('Shift not found.');
            if ($shift['status'] !== 'open') throw new RuntimeException('Shift is already closed.');

            $sales = shift_calc_sales($pdo, $shiftId);
            $variance = $countedCash - (float)$sales['expected_cash'];

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("
                UPDATE pos_shifts
                SET closed_by=:closed_by,
                    closed_at=NOW(),
                    expected_cash=:expected_cash,
                    counted_cash=:counted_cash,
                    variance=:variance,
                    total_sales=:total_sales,
                    cash_sales=:cash_sales,
                    card_sales=:card_sales,
                    transfer_sales=:transfer_sales,
                    room_charge_sales=:room_charge_sales,
                    complimentary_sales=:complimentary_sales,
                    void_sales=:void_sales,
                    receipt_count=:receipt_count,
                    status='closed',
                    closing_notes=:closing_notes
                WHERE id=:id
            ");
            $stmt->execute([
                ':closed_by' => $userId ?: null,
                ':expected_cash' => $sales['expected_cash'],
                ':counted_cash' => $countedCash,
                ':variance' => $variance,
                ':total_sales' => $sales['total_sales'],
                ':cash_sales' => $sales['cash_sales'],
                ':card_sales' => $sales['card_sales'],
                ':transfer_sales' => $sales['transfer_sales'],
                ':room_charge_sales' => $sales['room_charge_sales'],
                ':complimentary_sales' => $sales['complimentary_sales'],
                ':void_sales' => $sales['void_sales'],
                ':receipt_count' => $sales['receipts'],
                ':closing_notes' => $notes ?: null,
                ':id' => $shiftId,
            ]);

            $stmt = $pdo->prepare("
                INSERT INTO pos_shift_events
                (shift_id, event_type, amount, notes, created_by)
                VALUES
                (:shift_id, 'close', :amount, :notes, :created_by)
            ");
            $stmt->execute([
                ':shift_id' => $shiftId,
                ':amount' => $countedCash,
                ':notes' => $notes ?: 'Shift closed',
                ':created_by' => $userId ?: null,
            ]);

            $pdo->commit();

            shift_flash($variance == 0 ? 'success' : 'warning', 'Shift closed. Variance: ' . money_fmt($variance));
            header('Location: pos_shifts.php?view_id=' . $shiftId);
            exit;
        }

        if ($action === 'add_note') {
            $shiftId = (int)($_POST['shift_id'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($shiftId <= 0) throw new RuntimeException('Invalid shift.');
            if ($notes === '') throw new RuntimeException('Note is required.');

            $stmt = $pdo->prepare("
                INSERT INTO pos_shift_events
                (shift_id, event_type, amount, notes, created_by)
                VALUES
                (:shift_id, 'note', 0, :notes, :created_by)
            ");
            $stmt->execute([
                ':shift_id' => $shiftId,
                ':notes' => $notes,
                ':created_by' => $userId ?: null,
            ]);

            shift_flash('success', 'Shift note added.');
            header('Location: pos_shifts.php?view_id=' . $shiftId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        shift_flash('danger', $e->getMessage());
        header('Location: pos_shifts.php');
        exit;
    }
}

$stores = [];
try {
    $stores = $pdo->query("SELECT * FROM store_locations WHERE is_active=1 ORDER BY is_pos_location DESC, location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load stores: ' . $e->getMessage();
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$storeId = (int)($_GET['store_id'] ?? 0);
$status = trim((string)($_GET['status'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp;
}

$where = "DATE(ps.opened_at) BETWEEN :date_from AND :date_to";
$params = [':date_from' => $dateFrom, ':date_to' => $dateTo];

if ($storeId > 0) {
    $where .= " AND ps.store_id=:store_id";
    $params[':store_id'] = $storeId;
}
if ($status !== '') {
    $where .= " AND ps.status=:status";
    $params[':status'] = $status;
}
if ($search !== '') {
    $where .= " AND (ps.shift_no LIKE :q OR sl.location_name LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}

$userNameExpr = shift_user_name_expr($pdo, 'u');

$shifts = [];
$summary = [
    'open' => 0,
    'closed' => 0,
    'sales' => 0,
    'expected_cash' => 0,
    'counted_cash' => 0,
    'variance' => 0,
];

try {
    $userJoin = shift_table_exists($pdo, 'users') ? "LEFT JOIN users u ON u.id = ps.cashier_id" : "";
    $stmt = $pdo->prepare("
        SELECT
            ps.*,
            sl.location_name,
            {$userNameExpr} AS cashier_name
        FROM pos_shifts ps
        LEFT JOIN store_locations sl ON sl.id = ps.store_id
        {$userJoin}
        WHERE $where
        ORDER BY ps.opened_at DESC, ps.id DESC
        LIMIT 500
    ");
    $stmt->execute($params);
    $shifts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($shifts as $s) {
        if ($s['status'] === 'open') $summary['open']++;
        if ($s['status'] === 'closed') $summary['closed']++;
        $summary['sales'] += (float)$s['total_sales'];
        $summary['expected_cash'] += (float)$s['expected_cash'];
        $summary['counted_cash'] += (float)$s['counted_cash'];
        $summary['variance'] += (float)$s['variance'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load shifts: ' . $e->getMessage();
}

$openShifts = [];
try {
    $stmt = $pdo->query("
        SELECT ps.*, sl.location_name
        FROM pos_shifts ps
        LEFT JOIN store_locations sl ON sl.id = ps.store_id
        WHERE ps.status='open'
        ORDER BY ps.opened_at ASC
    ");
    $openShifts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewShift = null;
$viewSales = null;
$viewOrders = [];
$viewEvents = [];

if ($viewId > 0) {
    try {
        $userJoin = shift_table_exists($pdo, 'users') ? "LEFT JOIN users u ON u.id = ps.cashier_id" : "";
        $stmt = $pdo->prepare("
            SELECT ps.*, sl.location_name, {$userNameExpr} AS cashier_name
            FROM pos_shifts ps
            LEFT JOIN store_locations sl ON sl.id = ps.store_id
            {$userJoin}
            WHERE ps.id=:id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewShift = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewShift) {
            $viewSales = shift_calc_sales($pdo, $viewId);
            $end = !empty($viewShift['closed_at']) ? $viewShift['closed_at'] : date('Y-m-d H:i:s');

            $stmt = $pdo->prepare("
                SELECT *
                FROM pos_orders
                WHERE store_id=:store_id
                  AND created_at BETWEEN :opened_at AND :closed_at
                ORDER BY created_at DESC
                LIMIT 300
            ");
            $stmt->execute([
                ':store_id' => (int)$viewShift['store_id'],
                ':opened_at' => $viewShift['opened_at'],
                ':closed_at' => $end,
            ]);
            $viewOrders = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $pdo->prepare("
                SELECT *
                FROM pos_shift_events
                WHERE shift_id=:shift_id
                ORDER BY created_at DESC, id DESC
            ");
            $stmt->execute([':shift_id' => $viewId]);
            $viewEvents = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load shift detail: ' . $e->getMessage();
    }
}

$flashes = shift_get_flash();

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

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-person-badge"></i> POS Controls</div>
            <div class="hero-title mt-2">Cashier Shift Control</div>
            <div class="hero-subtitle mt-2">
                Open shifts, control floats, cash drops, close cash and monitor cash variance.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="pos.php" class="btn btn-light me-2"><i class="bi bi-cash-register me-2"></i>Open POS</a>
            <a href="pos_orders.php" class="btn btn-outline-light"><i class="bi bi-receipt me-2"></i>POS Orders</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?> no-print"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<?php if ($viewShift): ?>
<div class="card panel-card mb-4 shift-view" id="shiftPrint">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0"><?php echo h($viewShift['shift_no']); ?></h5>
            <div class="small text-muted"><?php echo h($viewShift['location_name'] ?: 'POS Store'); ?> • <?php echo h($viewShift['cashier_name'] ?: 'Cashier'); ?></div>
        </div>
        <div class="d-flex gap-2 no-print">
            <button type="button" onclick="window.print()" class="btn btn-sm btn-outline-primary"><i class="bi bi-printer me-1"></i>Print</button>
            <a href="pos_shifts.php" class="btn btn-sm btn-outline-secondary">Close</a>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-4">
            <div class="col-md-3"><strong>Status</strong><br><span class="badge <?php echo $viewShift['status'] === 'open' ? 'text-bg-success' : 'text-bg-secondary'; ?>"><?php echo h(ucwords($viewShift['status'])); ?></span></div>
            <div class="col-md-3"><strong>Opened</strong><br><?php echo h($viewShift['opened_at']); ?></div>
            <div class="col-md-3"><strong>Closed</strong><br><?php echo h($viewShift['closed_at'] ?: 'Still open'); ?></div>
            <div class="col-md-3 text-md-end"><strong>Variance</strong><br><span class="fs-5 fw-bold <?php echo (float)$viewShift['variance'] != 0 ? 'text-danger' : 'text-success'; ?>"><?php echo money_fmt($viewShift['variance']); ?></span></div>
        </div>

        <?php
            $liveExpected = $viewSales ? (float)$viewSales['expected_cash'] : 0;
            $liveVariance = (float)($viewShift['counted_cash'] ?? 0) - $liveExpected;
        ?>

        <div class="row g-4 mb-4">
            <div class="col-md-3"><div class="mini-stat"><span>Opening Float</span><strong><?php echo money_fmt($viewShift['opening_float']); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Cash Sales</span><strong><?php echo money_fmt($viewSales['cash_sales'] ?? 0); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Cash Drops</span><strong><?php echo money_fmt($viewShift['cash_drops']); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Expected Cash</span><strong><?php echo money_fmt($liveExpected); ?></strong></div></div>
        </div>

        <div class="row g-4 mb-4">
            <div class="col-md-3"><div class="mini-stat"><span>Total Sales</span><strong><?php echo money_fmt($viewSales['total_sales'] ?? 0); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Card</span><strong><?php echo money_fmt($viewSales['card_sales'] ?? 0); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Transfer</span><strong><?php echo money_fmt($viewSales['transfer_sales'] ?? 0); ?></strong></div></div>
            <div class="col-md-3"><div class="mini-stat"><span>Room Charge</span><strong><?php echo money_fmt($viewSales['room_charge_sales'] ?? 0); ?></strong></div></div>
        </div>

        <?php if ($viewShift['status'] === 'open'): ?>
            <div class="row g-3 no-print mb-4">
                <div class="col-lg-4">
                    <div class="action-box">
                        <h6>Cash Drop</h6>
                        <form method="post">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="cash_drop">
                            <input type="hidden" name="shift_id" value="<?php echo (int)$viewShift['id']; ?>">
                            <input type="number" step="0.01" name="amount" class="form-control mb-2" placeholder="Amount" required>
                            <input type="text" name="notes" class="form-control mb-2" placeholder="Notes">
                            <button class="btn btn-outline-primary w-100">Record Cash Drop</button>
                        </form>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="action-box">
                        <h6>Petty Cash Out</h6>
                        <form method="post">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="petty_cash_out">
                            <input type="hidden" name="shift_id" value="<?php echo (int)$viewShift['id']; ?>">
                            <input type="number" step="0.01" name="amount" class="form-control mb-2" placeholder="Amount" required>
                            <input type="text" name="notes" class="form-control mb-2" placeholder="Reason">
                            <button class="btn btn-outline-warning w-100">Record Petty Cash</button>
                        </form>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="action-box close-box">
                        <h6>Close Shift</h6>
                        <form method="post" onsubmit="return confirm('Close this shift?');">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="close_shift">
                            <input type="hidden" name="shift_id" value="<?php echo (int)$viewShift['id']; ?>">
                            <input type="number" step="0.01" name="counted_cash" class="form-control mb-2" placeholder="Actual cash counted" required>
                            <input type="text" name="closing_notes" class="form-control mb-2" placeholder="Closing notes">
                            <button class="btn btn-success w-100">Close Shift</button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-xl-7">
                <h6 class="fw-bold">Shift Receipts</h6>
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead><tr><th>Date</th><th>Receipt</th><th>Payment</th><th>Status</th><th class="text-end">Total</th></tr></thead>
                        <tbody>
                        <?php if (!$viewOrders): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3">No receipts in this shift.</td></tr>
                        <?php else: foreach ($viewOrders as $o): ?>
                            <tr class="<?php echo $o['status'] === 'void' ? 'table-danger' : ''; ?>">
                                <td><?php echo h(date('Y-m-d H:i', strtotime($o['created_at']))); ?></td>
                                <td><strong><?php echo h($o['pos_no']); ?></strong></td>
                                <td><?php echo h(ucwords(str_replace('_',' ', $o['payment_method'] ?: '—'))); ?></td>
                                <td><?php echo h(ucwords(str_replace('_',' ', $o['status']))); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($o['total_amount']); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="col-xl-5">
                <h6 class="fw-bold">Shift Audit Trail</h6>
                <div class="timeline-box">
                    <?php if (!$viewEvents): ?>
                        <div class="text-muted">No events yet.</div>
                    <?php else: foreach ($viewEvents as $ev): ?>
                        <div class="timeline-item">
                            <div class="timeline-dot"></div>
                            <div>
                                <strong><?php echo h(ucwords(str_replace('_',' ', $ev['event_type']))); ?></strong>
                                <?php if ((float)$ev['amount'] != 0): ?> • <?php echo money_fmt($ev['amount']); ?><?php endif; ?>
                                <div class="small text-muted"><?php echo h($ev['created_at']); ?></div>
                                <?php if (!empty($ev['notes'])): ?><div><?php echo h($ev['notes']); ?></div><?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; endif; ?>
                </div>

                <form method="post" class="mt-3 no-print">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="add_note">
                    <input type="hidden" name="shift_id" value="<?php echo (int)$viewShift['id']; ?>">
                    <div class="input-group">
                        <input type="text" name="notes" class="form-control" placeholder="Add audit note">
                        <button class="btn btn-outline-secondary">Add</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-4 mb-4 no-print">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-unlock"></i></div><div><div class="metric-label">Open Shifts</div><div class="metric-value"><?php echo (int)$summary['open']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-lock"></i></div><div><div class="metric-label">Closed Shifts</div><div class="metric-value"><?php echo (int)$summary['closed']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-cash-stack"></i></div><div><div class="metric-label">Sales</div><div class="metric-value small-value"><?php echo money_fmt($summary['sales']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon <?php echo abs((float)$summary['variance']) > 0.01 ? 'bg-danger-subtle text-danger' : 'bg-success-subtle text-success'; ?>"><i class="bi bi-balance-scale"></i></div><div><div class="metric-label">Variance</div><div class="metric-value small-value"><?php echo money_fmt($summary['variance']); ?></div></div></div></div>
</div>

<div class="row g-4 no-print">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Open New Shift</h5></div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="open_shift">

                    <div class="mb-3">
                        <label class="form-label">POS Store</label>
                        <select name="store_id" class="form-select" required>
                            <option value="">Select store</option>
                            <?php foreach ($stores as $s): ?>
                                <?php if ((int)$s['is_pos_location'] === 1): ?>
                                    <option value="<?php echo (int)$s['id']; ?>"><?php echo h($s['location_name']); ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Opening Float</label>
                        <input type="number" step="0.01" min="0" name="opening_float" class="form-control" value="0.00">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Opening Notes</label>
                        <textarea name="opening_notes" class="form-control" rows="3"></textarea>
                    </div>

                    <button class="btn btn-primary w-100"><i class="bi bi-unlock me-2"></i>Open Shift</button>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Currently Open</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern mb-0">
                    <thead><tr><th>Shift</th><th>Store</th><th class="text-end">Float</th></tr></thead>
                    <tbody>
                    <?php if (!$openShifts): ?>
                        <tr><td colspan="3" class="text-center text-muted py-4">No open shifts.</td></tr>
                    <?php else: foreach ($openShifts as $s): ?>
                        <tr>
                            <td><a href="pos_shifts.php?view_id=<?php echo (int)$s['id']; ?>"><strong><?php echo h($s['shift_no']); ?></strong></a><div class="small text-muted"><?php echo h($s['opened_at']); ?></div></td>
                            <td><?php echo h($s['location_name']); ?></td>
                            <td class="text-end"><?php echo money_fmt($s['opening_float']); ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-2"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>"></div>
                    <div class="col-md-2"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>"></div>
                    <div class="col-md-3">
                        <label class="form-label">Store</label>
                        <select name="store_id" class="form-select">
                            <option value="0">All stores</option>
                            <?php foreach ($stores as $s): ?>
                                <option value="<?php echo (int)$s['id']; ?>" <?php echo $storeId === (int)$s['id'] ? 'selected' : ''; ?>><?php echo h($s['location_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="open" <?php echo $status === 'open' ? 'selected' : ''; ?>>Open</option>
                            <option value="closed" <?php echo $status === 'closed' ? 'selected' : ''; ?>>Closed</option>
                        </select>
                    </div>
                    <div class="col-md-2"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>"></div>
                    <div class="col-md-1 d-grid"><button class="btn btn-primary"><i class="bi bi-funnel"></i></button></div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Shift History</h5>
                <span class="text-muted small">Latest 500 shifts</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Shift</th>
                            <th>Store</th>
                            <th>Opened</th>
                            <th>Closed</th>
                            <th>Status</th>
                            <th class="text-end">Sales</th>
                            <th class="text-end">Expected</th>
                            <th class="text-end">Counted</th>
                            <th class="text-end">Variance</th>
                            <th class="text-end">Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$shifts): ?>
                            <tr><td colspan="10" class="text-center text-muted py-4">No shifts found.</td></tr>
                        <?php else: foreach ($shifts as $s): ?>
                            <tr class="<?php echo abs((float)$s['variance']) > 0.01 ? 'table-warning' : ''; ?>">
                                <td><strong><?php echo h($s['shift_no']); ?></strong><div class="small text-muted"><?php echo h($s['cashier_name'] ?: 'Cashier'); ?></div></td>
                                <td><?php echo h($s['location_name'] ?: 'Store'); ?></td>
                                <td><?php echo h(date('Y-m-d H:i', strtotime($s['opened_at']))); ?></td>
                                <td><?php echo $s['closed_at'] ? h(date('Y-m-d H:i', strtotime($s['closed_at']))) : '—'; ?></td>
                                <td><span class="badge <?php echo $s['status'] === 'open' ? 'text-bg-success' : 'text-bg-secondary'; ?>"><?php echo h(ucwords($s['status'])); ?></span></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($s['total_sales']); ?></td>
                                <td class="text-end"><?php echo money_fmt($s['expected_cash']); ?></td>
                                <td class="text-end"><?php echo $s['counted_cash'] === null ? '—' : money_fmt($s['counted_cash']); ?></td>
                                <td class="text-end fw-bold <?php echo abs((float)$s['variance']) > 0.01 ? 'text-danger' : 'text-success'; ?>"><?php echo money_fmt($s['variance']); ?></td>
                                <td class="text-end"><a href="pos_shifts.php?view_id=<?php echo (int)$s['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.shift-view{border:2px solid rgba(37,99,235,.18)}
.mini-stat{background:#f8fafc;border:1px solid rgba(15,23,42,.08);border-radius:18px;padding:14px}
.mini-stat span{display:block;color:#64748b;font-size:12px;text-transform:uppercase;font-weight:900;letter-spacing:.04em}
.mini-stat strong{display:block;font-size:1.25rem;font-weight:950;color:#0f172a}
.action-box{border:1px solid rgba(15,23,42,.10);background:#f8fafc;border-radius:18px;padding:14px}
.close-box{background:#ecfdf5;border-color:#bbf7d0}
.timeline-box{display:flex;flex-direction:column;gap:12px}
.timeline-item{display:grid;grid-template-columns:16px 1fr;gap:10px}
.timeline-dot{width:12px;height:12px;border-radius:50%;background:#2563eb;margin-top:5px}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    #shiftPrint{box-shadow:none!important;border:0!important}
    .panel-card,.card,.metric-card{box-shadow:none!important}
}
</style>

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