<?php
session_start();
header('Content-Type: application/json');
require "../config/db_connect.php";

/* 1️⃣ Check login */
if (!isset($_SESSION['user']['id'])) {
    http_response_code(401);
    echo json_encode([
        "status" => "error",
        "message" => "Unauthorized"
    ]);
    exit;
}

/* 2️⃣ Collectn input safely */
$shop_name   = trim($_POST['shop_name'] ?? '');
$phone       = trim($_POST['phone'] ?? '');
$address     = trim($_POST['address'] ?? '');
$shop_status = $_POST['shop_status'] ?? 0;
$created_by  = $_SESSION['user']['id'];

/* 3️⃣ Validate */
if ($shop_name === '') {
    http_response_code(400);
    echo json_encode([
        "status" => "error",
        "message" => "Shop name required"
    ]);
    exit;
}

/* 4️⃣ Save to DB */
try {
    $stmt = $pdo->prepare("
        INSERT INTO shops (name, phone, address, is_active, created_by)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $shop_name,
        $phone,
        $address,
        $shop_status,
        $created_by
    ]);

    echo json_encode([
        "status" => "success",
        "message" => "Shop saved"
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        "status" => "error",
        "message" => "Shop NOT created"
    ]);
}
