<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
header('Content-Type: application/json');

// Check admin role
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

include('../../includes/config.php');

$userId = $_SESSION['user_id'];
$roleId = $_SESSION['role_id'];
$deviceInfo = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

// Helper: Insert audit log record
function audit_log($conn, $userId, $roleId, $action, $details, $module, $deviceInfo) {
    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, details, module, device_info) VALUES (?, ?, ?, ?, ?, ?)");
    if (!$stmt) return false;
    $stmt->bind_param("iissss", $userId, $roleId, $action, $details, $module, $deviceInfo);
    $result = $stmt->execute();
    $stmt->close();
    return $result;
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

if ($id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid store ID']);
    exit();
}

// 1. Check if there are users associated with the store
$check_users_sql = "SELECT COUNT(*) AS user_count FROM users WHERE store_id = ?";
if ($stmt = $conn->prepare($check_users_sql)) {
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($user_count);
    $stmt->fetch();
    $stmt->close();

    if ($user_count > 0) {
        http_response_code(409); // Conflict
        echo json_encode([
            'success' => false,
            'message' => 'This store cannot be deleted because it is associated with users. Please remove all users before deleting the store.'
        ]);
        exit();
    }
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to check store associations: ' . $conn->error]);
    exit();
}

// 2. Fetch store details for audit logging
$store_name = '';
$store_address = '';
$sql_fetch = "SELECT store_name, store_address FROM stores WHERE id = ?";
if ($stmt = $conn->prepare($sql_fetch)) {
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($store_name, $store_address);
    $stmt->fetch();
    $stmt->close();
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to fetch store details: ' . $conn->error]);
    exit();
}

if (empty($store_name)) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'No store found with the provided ID']);
    exit();
}

// 3. Delete the store
$sql = "DELETE FROM stores WHERE id = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $id);

    if (!$stmt->execute()) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to delete store: ' . $stmt->error]);
        $stmt->close();
        $conn->close();
        exit();
    }

    if ($stmt->affected_rows === 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'No store found with the provided ID']);
        $stmt->close();
        $conn->close();
        exit();
    }

    // Prepare audit log details as JSON
    $detailsArr = [
        'store_id' => $id,
        'store_name' => $store_name,
        'store_address' => $store_address
    ];
    $details = json_encode($detailsArr, JSON_UNESCAPED_UNICODE);

    // Insert audit log entry
    audit_log($conn, $userId, $roleId, 'Delete Store', $details, 'stores', $deviceInfo);

    echo json_encode(['success' => true, 'message' => 'Store deleted successfully']);
    $stmt->close();
    $conn->close();
    exit();
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to prepare delete statement: ' . $conn->error]);
    exit();
}
