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

$pageTitle = 'Store Locations';

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('sl_flash')) {
    function sl_flash(string $type, string $message): void {
        $_SESSION['store_locations_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('sl_get_flash')) {
    function sl_get_flash(): array {
        $items = $_SESSION['store_locations_flash'] ?? [];
        unset($_SESSION['store_locations_flash']);
        return $items;
    }
}
if (!function_exists('sl_bool')) {
    function sl_bool($value): int {
        return in_array((string)$value, ['1','yes','true','on'], true) ? 1 : 0;
    }
}

$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),
        INDEX idx_store_location_active (is_active),
        INDEX idx_store_location_pos (is_pos_location)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // Safely upgrade older store_locations table versions.
    $colCheck = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = 'store_locations'
          AND column_name = :col
    ");

    foreach ([
        'allow_room_charge' => "ALTER TABLE store_locations ADD COLUMN allow_room_charge TINYINT(1) NOT NULL DEFAULT 1 AFTER is_pos_location",
        'notes' => "ALTER TABLE store_locations ADD COLUMN notes TEXT NULL AFTER is_active"
    ] as $col => $sql) {
        $colCheck->execute([':col' => $col]);
        if ((int)$colCheck->fetchColumn() === 0) {
            $pdo->exec($sql);
        }
    }

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code),
        INDEX idx_inventory_item_name (item_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_movements (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        movement_type ENUM('OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN') NOT NULL,
        qty_in DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        qty_out DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reference_type VARCHAR(60) NULL,
        reference_id BIGINT UNSIGNED NULL,
        notes TEXT NULL,
        movement_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_stock_item_store (item_id, store_id),
        INDEX idx_stock_movement_date (movement_date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare store location tables: ' . $e->getMessage();
}

$typeLabels = [
    'main_store'=>'Main Store','bar'=>'Bar','restaurant'=>'Restaurant','curio'=>'Curio Shop',
    'kitchen'=>'Kitchen','housekeeping'=>'Housekeeping','maintenance'=>'Maintenance','other'=>'Other'
];

$typeIcons = [
    'main_store'=>'bi-box-seam','bar'=>'bi-cup-straw','restaurant'=>'bi-egg-fried','curio'=>'bi-gem',
    'kitchen'=>'bi-fire','housekeeping'=>'bi-brush','maintenance'=>'bi-tools','other'=>'bi-shop'
];

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

        if ($action === 'save_location') {
            $id = (int)($_POST['id'] ?? 0);
            $locationCode = strtoupper(trim((string)($_POST['location_code'] ?? '')));
            $locationName = trim((string)($_POST['location_name'] ?? ''));
            $locationType = (string)($_POST['location_type'] ?? 'main_store');
            $isPosLocation = sl_bool($_POST['is_pos_location'] ?? 0);
            $allowRoomCharge = sl_bool($_POST['allow_room_charge'] ?? 0);
            $isActive = sl_bool($_POST['is_active'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($locationName === '') throw new RuntimeException('Store/location name is required.');
            if (!isset($typeLabels[$locationType])) $locationType = 'main_store';
            if ($locationCode === '') {
                $prefix = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $locationName), 0, 5));
                $locationCode = ($prefix ?: 'STORE') . '-' . date('His');
            }

            $payload = [
                ':location_code'=>$locationCode,
                ':location_name'=>$locationName,
                ':location_type'=>$locationType,
                ':is_pos_location'=>$isPosLocation,
                ':allow_room_charge'=>$allowRoomCharge,
                ':is_active'=>$isActive,
                ':notes'=>$notes !== '' ? $notes : null
            ];

            if ($id > 0) {
                $payload[':id'] = $id;
                $stmt = $pdo->prepare("UPDATE store_locations SET
                    location_code=:location_code, location_name=:location_name, location_type=:location_type,
                    is_pos_location=:is_pos_location, allow_room_charge=:allow_room_charge,
                    is_active=:is_active, notes=:notes
                    WHERE id=:id");
                $stmt->execute($payload);
                sl_flash('success', 'Store location updated successfully.');
            } else {
                $stmt = $pdo->prepare("INSERT INTO store_locations
                    (location_code, location_name, location_type, is_pos_location, allow_room_charge, is_active, notes)
                    VALUES
                    (:location_code, :location_name, :location_type, :is_pos_location, :allow_room_charge, :is_active, :notes)");
                $stmt->execute($payload);
                sl_flash('success', 'Store location created successfully.');
            }

            header('Location: store_locations.php');
            exit;
        }

        if ($action === 'toggle_location') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid store location selected.');
            $stmt = $pdo->prepare("UPDATE store_locations SET is_active = CASE WHEN is_active=1 THEN 0 ELSE 1 END WHERE id=:id");
            $stmt->execute([':id'=>$id]);
            sl_flash('success', 'Store location status updated.');
            header('Location: store_locations.php');
            exit;
        }

        if ($action === 'delete_location') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid store location selected.');

            $pdo->beginTransaction();

            try {
                $stmt = $pdo->prepare("SELECT location_name, is_active FROM store_locations WHERE id=:id FOR UPDATE");
                $stmt->execute([':id'=>$id]);
                $store = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$store) {
                    throw new RuntimeException('Store location was not found.');
                }

                $stmt = $pdo->prepare("SELECT COUNT(*) FROM stock_movements WHERE store_id=:id");
                $stmt->execute([':id'=>$id]);
                $movementCount = (int)$stmt->fetchColumn();

                if ($movementCount > 0) {
                    $stmt = $pdo->prepare("UPDATE store_locations SET is_active=0 WHERE id=:id");
                    $stmt->execute([':id'=>$id]);
                    $pdo->commit();

                    sl_flash('warning', 'Store "' . $store['location_name'] . '" has ' . $movementCount . ' stock movement(s), so it was deactivated instead of deleted.');
                } else {
                    $stmt = $pdo->prepare("DELETE FROM store_locations WHERE id=:id");
                    $stmt->execute([':id'=>$id]);
                    $pdo->commit();

                    sl_flash('success', 'Store "' . $store['location_name'] . '" had no stock movements and was permanently deleted.');
                }
            } catch (Throwable $inner) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $inner;
            }

            header('Location: store_locations.php');
            exit;
        }
    } catch (Throwable $e) {
        sl_flash('danger', $e->getMessage());
        header('Location: store_locations.php');
        exit;
    }
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editLocation = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM store_locations WHERE id=:id LIMIT 1");
    $stmt->execute([':id'=>$editId]);
    $editLocation = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$filterType = trim((string)($_GET['location_type'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$filterPos = trim((string)($_GET['pos'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

$where = '1=1';
$params = [];
if ($filterType !== '') { $where .= ' AND sl.location_type=:location_type'; $params[':location_type'] = $filterType; }
if ($filterStatus !== '') { $where .= ' AND sl.is_active=:is_active'; $params[':is_active'] = (int)$filterStatus; }
if ($filterPos !== '') { $where .= ' AND sl.is_pos_location=:is_pos_location'; $params[':is_pos_location'] = (int)$filterPos; }
if ($search !== '') {
    // Use unique placeholders for each LIKE clause.
    // Some PDO/MySQL setups throw SQLSTATE[HY093] when the same named placeholder is reused.
    $where .= ' AND (sl.location_name LIKE :q_name OR sl.location_code LIKE :q_code OR sl.notes LIKE :q_notes)';
    $searchLike = '%' . $search . '%';
    $params[':q_name'] = $searchLike;
    $params[':q_code'] = $searchLike;
    $params[':q_notes'] = $searchLike;
}

$locations = [];
$summary = ['total'=>0,'active'=>0,'pos'=>0,'room_charge'=>0,'stock_value'=>0,'protected'=>0,'deletable'=>0];

try {
    $stmt = $pdo->prepare("SELECT sl.*,
        COALESCE(sb.item_count,0) AS item_count,
        COALESCE(sb.movement_count,0) AS movement_count,
        COALESCE(sb.total_qty,0) AS total_qty,
        COALESCE(sb.stock_value,0) AS stock_value
        FROM store_locations sl
        LEFT JOIN (
            SELECT store_id, COUNT(DISTINCT item_id) AS item_count,
                   COUNT(*) AS movement_count,
                   SUM(qty_in-qty_out) AS total_qty,
                   SUM((qty_in-qty_out)*unit_cost) AS stock_value
            FROM stock_movements
            GROUP BY store_id
        ) sb ON sb.store_id=sl.id
        WHERE $where
        ORDER BY sl.is_active DESC, sl.is_pos_location DESC, sl.location_type ASC, sl.location_name ASC");
    $stmt->execute($params);
    $locations = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($locations as $row) {
        $summary['total']++;
        if ((int)$row['is_active'] === 1) $summary['active']++;
        if ((int)$row['is_pos_location'] === 1) $summary['pos']++;
        if ((int)$row['allow_room_charge'] === 1) $summary['room_charge']++;
        if ((int)($row['movement_count'] ?? 0) > 0) $summary['protected']++;
        if ((int)($row['movement_count'] ?? 0) === 0) $summary['deletable']++;
        $summary['stock_value'] += (float)$row['stock_value'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load store locations: ' . $e->getMessage();
}


if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    try {
        $exportStmt = $pdo->prepare("SELECT sl.*,
            COALESCE(sb.item_count,0) AS item_count,
            COALESCE(sb.movement_count,0) AS movement_count,
            COALESCE(sb.total_qty,0) AS total_qty,
            COALESCE(sb.stock_value,0) AS stock_value
            FROM store_locations sl
            LEFT JOIN (
                SELECT store_id, COUNT(DISTINCT item_id) AS item_count,
                       COUNT(*) AS movement_count,
                       SUM(qty_in-qty_out) AS total_qty,
                       SUM((qty_in-qty_out)*unit_cost) AS stock_value
                FROM stock_movements
                GROUP BY store_id
            ) sb ON sb.store_id=sl.id
            WHERE $where
            ORDER BY sl.is_active DESC, sl.is_pos_location DESC, sl.location_type ASC, sl.location_name ASC");
        $exportStmt->execute($params);
        $exportRows = $exportStmt->fetchAll(PDO::FETCH_ASSOC);

        $filename = 'store_locations_' . date('Ymd_His') . '.xls';
        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');

        echo "\xEF\xBB\xBF";
        echo '<table border="1">';
        echo '<tr>';
        foreach (['Code','Location Name','Type','POS Location','Allow Room Charge','Status','Items','Movements','Qty Balance','Stock Value','Notes'] as $heading) {
            echo '<th>' . h($heading) . '</th>';
        }
        echo '</tr>';

        foreach ($exportRows as $row) {
            echo '<tr>';
            echo '<td>' . h($row['location_code'] ?: '') . '</td>';
            echo '<td>' . h($row['location_name'] ?: '') . '</td>';
            echo '<td>' . h($typeLabels[$row['location_type']] ?? ucwords((string)$row['location_type'])) . '</td>';
            echo '<td>' . ((int)$row['is_pos_location'] === 1 ? 'Yes' : 'No') . '</td>';
            echo '<td>' . ((int)$row['allow_room_charge'] === 1 ? 'Yes' : 'No') . '</td>';
            echo '<td>' . ((int)$row['is_active'] === 1 ? 'Active' : 'Inactive') . '</td>';
            echo '<td style="mso-number-format:\'0\'">' . (int)$row['item_count'] . '</td>';
            echo '<td style="mso-number-format:\'0\'">' . (int)$row['movement_count'] . '</td>';
            echo '<td style="mso-number-format:\'0.0000\'">' . h(number_format((float)$row['total_qty'], 4, '.', '')) . '</td>';
            echo '<td style="mso-number-format:\'0.00\'">' . h(number_format((float)$row['stock_value'], 2, '.', '')) . '</td>';
            echo '<td>' . h($row['notes'] ?: '') . '</td>';
            echo '</tr>';
        }

        echo '</table>';
        exit;
    } catch (Throwable $e) {
        sl_flash('danger', 'Could not export store locations: ' . $e->getMessage());
        header('Location: store_locations.php');
        exit;
    }
}

$recentMovements = [];
try {
    $recentMovements = $pdo->query("SELECT sm.*, ii.item_name, ii.item_code, sl.location_name, sl.location_code
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        ORDER BY sm.movement_date DESC, sm.id DESC
        LIMIT 12")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

$flashes = sl_get_flash();

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

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-shop"></i> Stores &amp; POS Inventory</div>
            <div class="hero-title mt-2">Store Locations</div>
            <div class="hero-subtitle mt-2">Manage main store, bar, restaurant, curio shop, kitchen and other stock locations.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <?php
                $exportQuery = $_GET;
                unset($exportQuery['edit_id']);
                $exportQuery['export'] = 'excel';
                $exportUrl = 'store_locations.php?' . http_build_query($exportQuery);
            ?>
            <a href="inventory_items.php" class="btn btn-light me-2"><i class="bi bi-box-seam me-2"></i>Items</a>
            <a href="stock_movements.php" class="btn btn-outline-light me-2"><i class="bi bi-arrow-left-right me-2"></i>Movements</a>
            <a href="<?php echo h($exportUrl); ?>" class="btn btn-success"><i class="bi bi-file-earmark-excel me-2"></i>Export Excel</a>
        </div>
    </div>
</div>

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

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <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; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-shop"></i></div><div><div class="metric-label">Locations</div><div class="metric-value"><?php echo (int)$summary['total']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div><div><div class="metric-label">Active</div><div class="metric-value"><?php echo (int)$summary['active']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-cash-register"></i></div><div><div class="metric-label">POS</div><div class="metric-value"><?php echo (int)$summary['pos']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-shield-lock"></i></div><div><div class="metric-label">Protected</div><div class="metric-value"><?php echo (int)$summary['protected']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-trash3"></i></div><div><div class="metric-label">Deletable</div><div class="metric-value"><?php echo (int)$summary['deletable']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-2"><div class="metric-card"><div class="metric-icon bg-info-subtle text-info"><i class="bi bi-cash-stack"></i></div><div><div class="metric-label">Stock Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['stock_value']); ?></div></div></div></div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0"><?php echo $editLocation ? 'Edit Store Location' : 'Add Store Location'; ?></h5></div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_location">
                    <input type="hidden" name="id" value="<?php echo (int)($editLocation['id'] ?? 0); ?>">

                    <div class="mb-3">
                        <label class="form-label">Location Code</label>
                        <input type="text" name="location_code" class="form-control" value="<?php echo h($editLocation['location_code'] ?? ''); ?>" placeholder="BAR / MAIN / CURIO">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Location Name</label>
                        <input type="text" name="location_name" class="form-control" required value="<?php echo h($editLocation['location_name'] ?? ''); ?>" placeholder="Bar Store">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Location Type</label>
                        <select name="location_type" class="form-select">
                            <?php foreach ($typeLabels as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo (($editLocation['location_type'] ?? 'main_store') === $value) ? 'selected' : ''; ?>>
                                    <?php echo h($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="settings-check-grid">
                        <label class="setting-check"><input type="checkbox" name="is_pos_location" value="1" <?php echo (int)($editLocation['is_pos_location'] ?? 0) === 1 ? 'checked' : ''; ?>><span>POS Location</span></label>
                        <label class="setting-check"><input type="checkbox" name="allow_room_charge" value="1" <?php echo (int)($editLocation['allow_room_charge'] ?? 1) === 1 ? 'checked' : ''; ?>><span>Allow Room Charge</span></label>
                        <label class="setting-check"><input type="checkbox" name="is_active" value="1" <?php echo (int)($editLocation['is_active'] ?? 1) === 1 ? 'checked' : ''; ?>><span>Active</span></label>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="3"><?php echo h($editLocation['notes'] ?? ''); ?></textarea>
                    </div>

                    <div class="d-grid gap-2 mt-4">
                        <button class="btn btn-primary"><i class="bi bi-save me-2"></i><?php echo $editLocation ? 'Update Location' : 'Create Location'; ?></button>
                        <?php if ($editLocation): ?><a href="store_locations.php" class="btn btn-outline-secondary">Cancel Edit</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Location Rules</h5></div>
            <div class="card-body small">
                <p><strong>Main Store:</strong> receives purchases and transfers stock to departments.</p>
                <p><strong>Bar / Restaurant / Curio:</strong> should be POS locations if sales happen there.</p>
                <p><strong>Room Charge:</strong> enable only where guests may post unpaid POS charges to their folio.</p>
                <p class="mb-0"><strong>Stock Value:</strong> comes from stock movements, not manual balances.</p>
            </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-4"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Name/code/notes"></div>
                    <div class="col-md-3"><label class="form-label">Type</label><select name="location_type" class="form-select"><option value="">All types</option><?php foreach ($typeLabels as $value => $label): ?><option value="<?php echo h($value); ?>" <?php echo $filterType === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-2"><label class="form-label">POS</label><select name="pos" class="form-select"><option value="">All</option><option value="1" <?php echo $filterPos === '1' ? 'selected' : ''; ?>>POS Only</option><option value="0" <?php echo $filterPos === '0' ? 'selected' : ''; ?>>Non POS</option></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="1" <?php echo $filterStatus === '1' ? 'selected' : ''; ?>>Active</option><option value="0" <?php echo $filterStatus === '0' ? 'selected' : ''; ?>>Inactive</option></select></div>
                    <div class="col-md-1 d-grid"><button class="btn btn-primary" title="Apply filters"><i class="bi bi-funnel"></i></button></div>
                    <div class="col-md-12 d-flex justify-content-end gap-2 filter-actions">
                        <a href="store_locations.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-x-circle me-1"></i>Clear</a>
                        <a href="<?php echo h($exportUrl); ?>" class="btn btn-success btn-sm"><i class="bi bi-file-earmark-excel me-1"></i>Export Filtered Stores</a>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Store Location Master</h5><span class="text-muted small"><?php echo count($locations); ?> location(s)</span></div>
            <div class="card-body p-0">
                <div class="store-table-wrap">
                    <table class="table table-modern align-middle mb-0 store-master-table">
                        <thead><tr><th>Location</th><th>Type</th><th class="text-end">Items</th><th class="text-end">Movements</th><th class="text-end">Qty Balance</th><th class="text-end">Stock Value</th><th>Flags</th><th class="text-end">Actions</th></tr></thead>
                        <tbody>
                        <?php if (!$locations): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No store locations found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($locations as $row): ?>
                                <?php $icon = $typeIcons[$row['location_type']] ?? 'bi-shop'; ?>
                                <tr>
                                    <td><div class="d-flex align-items-center gap-2"><span class="location-icon"><i class="bi <?php echo h($icon); ?>"></i></span><div><strong><?php echo h($row['location_name']); ?></strong><div class="small text-muted">Code: <?php echo h($row['location_code'] ?: '—'); ?></div></div></div></td>
                                    <td><?php echo h($typeLabels[$row['location_type']] ?? ucwords($row['location_type'])); ?></td>
                                    <td class="text-end"><?php echo (int)$row['item_count']; ?></td>
                                    <td class="text-end"><span class="history-pill <?php echo (int)$row['movement_count'] > 0 ? 'is-locked' : 'is-open'; ?>"><?php echo (int)$row['movement_count']; ?></span></td>
                                    <td class="text-end"><?php echo money_fmt($row['total_qty']); ?></td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($row['stock_value']); ?></td>
                                    <td><div class="d-flex flex-wrap gap-1"><?php if ((int)$row['is_pos_location'] === 1): ?><span class="badge text-bg-success">POS</span><?php endif; ?><?php if ((int)$row['allow_room_charge'] === 1): ?><span class="badge text-bg-info">Room Charge</span><?php endif; ?><span class="badge <?php echo (int)$row['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>"><?php echo (int)$row['is_active'] === 1 ? 'Active' : 'Inactive'; ?></span></div></td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="store_locations.php?edit_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary"><i class="bi bi-pencil"></i></a>
                                            <a href="stock_movements.php?store_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-info"><i class="bi bi-arrow-left-right"></i></a>
                                            <?php if ((int)$row['is_pos_location'] === 1): ?><a href="<?php echo defined('BASE_URL') ? BASE_URL : '/rooms'; ?>/modules/pos/pos.php?store_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-success"><i class="bi bi-cash-register"></i></a><?php endif; ?>
                                            <form method="post" class="d-inline"><?php if (function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="toggle_location"><input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>"><button class="btn btn-outline-secondary" title="<?php echo (int)$row['is_active'] === 1 ? 'Deactivate store' : 'Reactivate store'; ?>"><i class="bi <?php echo (int)$row['is_active'] === 1 ? 'bi-toggle-on' : 'bi-toggle-off'; ?>"></i></button></form>
                                            <?php if ((int)$row['movement_count'] > 0): ?>
                                                <form method="post" class="d-inline" onsubmit="return confirm('This store has stock history. It cannot be permanently deleted. It will be deactivated instead. Continue?');"><?php if (function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="delete_location"><input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>"><button class="btn btn-outline-warning" title="Protected by stock history - deactivate only"><i class="bi bi-archive"></i></button></form>
                                            <?php else: ?>
                                                <form method="post" class="d-inline" onsubmit="return confirm('This store has no stock movements and will be permanently deleted. Continue?');"><?php if (function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="delete_location"><input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>"><button class="btn btn-outline-danger" title="Delete permanently - no stock history"><i class="bi bi-trash"></i></button></form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php if (!empty($row['notes'])): ?><tr class="notes-row"><td colspan="8" class="small text-muted pt-0"><i class="bi bi-info-circle me-1"></i><?php echo h($row['notes']); ?></td></tr><?php endif; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Recent Stock Movements</h5></div>
            <div class="card-body p-0">
                <div class="recent-movement-wrap">
                    <table class="table table-modern align-middle mb-0 recent-movement-table">
                        <thead><tr><th>Date</th><th>Store</th><th>Item</th><th>Type</th><th class="text-end">In</th><th class="text-end">Out</th><th class="text-end">Value</th></tr></thead>
                        <tbody>
                        <?php if (!$recentMovements): ?>
                            <tr><td colspan="7" class="text-center text-muted py-4">No stock movements yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($recentMovements as $mv): ?>
                                <tr>
                                    <td><?php echo h($mv['movement_date']); ?></td>
                                    <td><?php echo h($mv['location_name'] ?: 'Store'); ?></td>
                                    <td><?php echo h($mv['item_name'] ?: 'Item'); ?><div class="small text-muted"><?php echo h($mv['item_code'] ?: ''); ?></div></td>
                                    <td><span class="badge text-bg-light border"><?php echo h($mv['movement_type']); ?></span></td>
                                    <td class="text-end"><?php echo money_fmt($mv['qty_in']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($mv['qty_out']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($mv['total_cost']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Compact Store Locations top section + export polish */
.hero-band{padding:12px 16px!important;margin-bottom:10px!important}
.hero-title{font-size:1.35rem!important;margin:2px 0!important;line-height:1.15!important}
.hero-subtitle{font-size:.82rem!important;line-height:1.25!important;margin-top:2px!important}
.page-eyebrow{font-size:.72rem!important;letter-spacing:.08em!important}
.hero-band .btn{padding:6px 10px!important;font-size:.8rem!important;border-radius:10px!important}
.hero-band .row.g-4{--bs-gutter-y:.5rem!important}
.row.g-4.mb-4{margin-bottom:10px!important;--bs-gutter-x:.65rem!important;--bs-gutter-y:.65rem!important}
.metric-card{padding:8px 9px!important;gap:7px!important;min-height:56px!important}
.metric-icon{width:30px!important;height:30px!important;font-size:13px!important;border-radius:10px!important}
.metric-value{font-size:1rem!important;line-height:1.05!important}
.metric-label{font-size:.7rem!important;margin-bottom:1px!important}
.card.panel-card{margin-bottom:10px!important;border-radius:16px!important}
.panel-card .card-header{padding:9px 12px!important}
.panel-card .card-header h5{font-size:.95rem!important}
.panel-card .card-body{padding:10px!important}
.form-label{font-size:.72rem!important;margin-bottom:2px!important;font-weight:700!important}
.form-control,.form-select{height:32px!important;min-height:32px!important;font-size:.82rem!important;padding:4px 8px!important;border-radius:9px!important}
textarea.form-control{height:auto!important;min-height:52px!important}
.row.g-3{--bs-gutter-x:.65rem!important;--bs-gutter-y:.55rem!important}
.mb-3{margin-bottom:.55rem!important}.mb-4{margin-bottom:.75rem!important}.mt-3{margin-top:.55rem!important}.mt-4{margin-top:.75rem!important}
.alert{padding:8px 12px!important;margin-bottom:10px!important;border-radius:12px!important}
.filter-actions .btn{border-radius:9px!important;font-weight:800!important}
.store-table-wrap{max-height:calc(100vh - 255px);overflow:auto;border-radius:0 0 16px 16px}
.recent-movement-wrap{max-height:260px;overflow:auto}
.table-modern thead th{position:sticky;top:0;z-index:8;background:linear-gradient(180deg,#ffffff,#f8fafc)!important;border-bottom:2px solid #e5e7eb!important;text-transform:uppercase;letter-spacing:.06em;font-weight:850;white-space:nowrap}
.table-modern th,.table-modern td{padding:7px 9px!important;vertical-align:middle!important}
.table-modern th{font-size:.72rem!important}.table-modern td{font-size:.82rem!important}.table-modern .small{font-size:.68rem!important;line-height:1.15!important}
.action-btns .btn,.btn-group .btn{min-width:29px!important;padding:4px 6px!important;border-radius:8px!important}

.small-value{font-size:1rem!important;letter-spacing:0!important}
.settings-check-grid{display:grid;grid-template-columns:1fr;gap:10px}
.setting-check{display:flex;align-items:center;gap:8px;border:1px solid rgba(15,23,42,.10);background:#fff;border-radius:14px;padding:10px 12px;font-weight:800;font-size:13px;color:#475569;cursor:pointer}
.setting-check input{width:16px;height:16px}
.location-icon{width:38px;height:38px;border-radius:13px;background:#eff6ff;color:#2563eb;display:inline-flex;align-items:center;justify-content:center;font-size:1rem;flex:0 0 auto}
.notes-row td{border-top:0!important;background:#fafafa}
.history-pill{display:inline-flex;align-items:center;justify-content:center;min-width:34px;height:26px;border-radius:999px;font-weight:900;font-size:12px;border:1px solid transparent}
.history-pill.is-locked{background:#fff7ed;color:#c2410c;border-color:#fed7aa}
.history-pill.is-open{background:#f8fafc;color:#475569;border-color:#e2e8f0}
.btn-group .btn{min-width:34px}


.store-master-table thead th:first-child{
    z-index:80;
    background:#ffffff!important;
}

/* Preserve warning/note row readability next to frozen column */
.notes-row td:first-child{
    position:static!important;
    box-shadow:none!important;
}

@media (max-width:991.98px){
    .store-master-table thead th,
    .recent-movement-table thead th{
        top:76px;
    }
}

@media print{
    .store-table-wrap,
    .recent-movement-wrap{
        overflow:visible!important;
    }
    .store-master-table thead th,
    .recent-movement-table thead th,
    .store-master-table th:first-child,
    .store-master-table td:first-child{
        position:static!important;
        box-shadow:none!important;
    }
}
</style>

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