<?php
// ajax/deactivate_product.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$product_id = $_POST['id'] ?? 0;

if ($product_id <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid product ID']);
    exit;
}

try {
    // Check if product exists and belongs to user's shop
    $user = $_SESSION['user'];
    $shop_id = $user['shop_id'];
    $user_role = $user['role'] ?? 'cashier';
    
    $sql = "SELECT p.id, p.name FROM products p WHERE p.id = ?";
    if ($user_role !== 'admin') {
        $sql .= " AND p.shop_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$product_id, $shop_id]);
    } else {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$product_id]);
    }
    
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        echo json_encode(['status' => 'error', 'message' => 'Product not found']);
        exit;
    }
    
    // Deactivate the product (soft delete)
    $stmt = $pdo->prepare("UPDATE products SET is_active = 0 WHERE id = ?");
    $stmt->execute([$product_id]);
    
    // Also deactivate all batches for this product
    $stmt = $pdo->prepare("UPDATE product_batches SET is_active = 0 WHERE product_id = ?");
    $stmt->execute([$product_id]);
    
    echo json_encode([
        'status' => 'success', 
        'message' => 'Product "' . htmlspecialchars($product['name']) . '" has been deactivated'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>