<?php
/**
 * Toggle Store Status (Activate/Deactivate)
 * Only store owners can toggle their own store status
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';

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

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$userId = $_SESSION['user_id'];
$storeId = intval($_POST['store_id'] ?? 0);
$newStatus = trim($_POST['status'] ?? '');

// Validate input
if ($storeId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store ID']);
    exit;
}

if (!in_array($newStatus, ['active', 'inactive'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid status. Must be "active" or "inactive"']);
    exit;
}

// Verify user owns this store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreById($storeId);

if (!$store) {
    echo json_encode(['success' => false, 'message' => 'Store not found']);
    exit;
}

if ($store['owner_id'] != $userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized. You can only manage your own store.']);
    exit;
}

// Update store status
$result = $storeManager->updateStore($storeId, ['status' => $newStatus]);

if ($result['success']) {
    echo json_encode([
        'success' => true,
        'message' => $newStatus === 'active' ? 'Store activated successfully' : 'Store deactivated successfully',
        'status' => $newStatus
    ]);
} else {
    echo json_encode($result);
}
?>

