<?php
require_once dirname(__DIR__, 2) . '/include/con_data.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$action = $_POST['action'] ?? '';

try {
    if ($action === 'add') {
        $shop_name = $_POST['shop_name'];
        $shop_code = $_POST['shop_code'];
        $phone = $_POST['phone'];
        $address = $_POST['address'];
        $status = $_POST['status'];

        $stmt = $pdo->prepare("INSERT INTO shops (shop_name, shop_code, phone, address, status) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$shop_name, $shop_code, $phone, $address, $status]);

        echo json_encode(['success' => true]);

    } elseif ($action === 'edit') {
        $shop_id = $_POST['shop_id'];
        $shop_name = $_POST['shop_name'];
        $shop_code = $_POST['shop_code'];
        $phone = $_POST['phone'];
        $address = $_POST['address'];
        $status = $_POST['status'];

        $stmt = $pdo->prepare("UPDATE shops SET shop_name=?, shop_code=?, phone=?, address=?, status=? WHERE shop_id=?");
        $stmt->execute([$shop_name, $shop_code, $phone, $address, $status, $shop_id]);

        echo json_encode(['success' => true]);

    } elseif ($action === 'delete') {
        $shop_id = $_POST['shop_id'];

        // Optional: Check if shop has users or data before deleting?
        // For now, allow delete.

        $stmt = $pdo->prepare("DELETE FROM shops WHERE shop_id = ?");
        $stmt->execute([$shop_id]);

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
