<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');
if (session_status() == PHP_SESSION_NONE) { session_start(); }

$action = $_REQUEST['action'] ?? '';
$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];
$user_id = $_SESSION['user_id'] ?? 0;

if ($action == 'get_stores') {
    $stores = $conn->query("SELECT id, store_name, created FROM cms_stores WHERE deleted = 0 ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);
    echo json_encode(['status' => 'success', 'data' => $stores]);
    exit();
}

if ($action == 'save_store') {
    $id = intval($_POST['id'] ?? 0);
    $store_name = trim($_POST['store_name'] ?? '');

    if (empty($store_name)) {
        $response['message'] = 'Tên kho không được để trống.';
    } else {
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE cms_stores SET store_name = ?, user_upd = ?, updated = NOW() WHERE id = ?");
            $stmt->bind_param('sii', $store_name, $user_id, $id);
        } else {
            $stmt = $conn->prepare("INSERT INTO cms_stores (store_name, user_init) VALUES (?, ?)");
            $stmt->bind_param('si', $store_name, $user_id);
        }

        if ($stmt && $stmt->execute()) {
            $response = ['status' => 'success', 'message' => 'Lưu kho thành công!'];
        } else {
            $response['message'] = 'Lỗi khi lưu kho: ' . ($stmt ? $stmt->error : $conn->error);
        }
        $stmt->close();
    }
    echo json_encode($response);
    exit();
}

if ($action == 'delete_store') {
    $id = intval($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE cms_stores SET deleted = 1, user_upd = ?, updated = NOW() WHERE id = ?");
        $stmt->bind_param('ii', $user_id, $id);
        if ($stmt && $stmt->execute()) {
            $response = ['status' => 'success', 'message' => 'Xóa kho thành công!'];
        } else {
            $response['message'] = 'Lỗi khi xóa kho: ' . ($stmt ? $stmt->error : $conn->error);
        }
        $stmt->close();
    } else {
        $response['message'] = 'ID kho không hợp lệ.';
    }
    echo json_encode($response);
    exit();
}

echo json_encode($response);
?>