<?php
include 'includes/auth.php';
include 'db.php';

// ==================== ADD STORE ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $store_name = $conn->real_escape_string($_POST['store_name']);
    $location = $conn->real_escape_string($_POST['location'] ?? '');
    $manager = $conn->real_escape_string($_POST['manager'] ?? '');

    // Check if store already exists
    $check = $conn->query("SELECT id FROM stores WHERE store_name='$store_name'")->fetch_assoc();
    if ($check) {
        echo "<script>alert('Store \"$store_name\" already exists.');window.location='products.php';</script>";
        exit;
    }

    // Insert store
    $stmt = $conn->prepare("INSERT INTO stores (store_name, location, manager) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $store_name, $location, $manager);
    if ($stmt->execute()) {
        echo "<script>alert('Store \"$store_name\" added successfully.');window.location='products.php';</script>";
        exit;
    } else {
        echo "Error: " . $stmt->error;
    }
} else {
    echo "<script>window.location='products.php';</script>";
}
