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

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

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

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
    exit;
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

// Get product ID
$product_id = $_POST['id'] ?? 0;

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

try {
    // Begin transaction
    $pdo->beginTransaction();
    
    // 1. Check if product exists and belongs to user's shop (unless admin)
    $user = $_SESSION['user'];
    $shop_id = $user['shop_id'];
    $user_role = $user['role'] ?? 'cashier';
    
    $sql = "SELECT p.id, p.name, COUNT(sl.id) as sale_count 
            FROM products p 
            LEFT JOIN sale_lines sl ON p.id = sl.product_id 
            WHERE p.id = ?";
    
    // Add shop filter for non-admin users
    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 or you do not have permission']);
        exit;
    }
    
    // 2. Check if product has been sold
    if ($product['sale_count'] > 0) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Cannot delete product "' . htmlspecialchars($product['name']) . '". It has been sold ' . $product['sale_count'] . ' time(s).'
        ]);
        exit;
    }
    
    // 3. Check if product has active batches with stock
    $sql_check_batches = "SELECT COUNT(*) as batch_count, SUM(bs.current_qty) as total_stock 
                          FROM batch_stock_view bs 
                          WHERE bs.product_id = ?";
    $stmt_check = $pdo->prepare($sql_check_batches);
    $stmt_check->execute([$product_id]);
    $batch_info = $stmt_check->fetch(PDO::FETCH_ASSOC);
    
    if ($batch_info['batch_count'] > 0 && $batch_info['total_stock'] > 0) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Cannot delete product "' . htmlspecialchars($product['name']) . '". It has ' . $batch_info['total_stock'] . ' units in stock across ' . $batch_info['batch_count'] . ' batch(es). Please sell or adjust stock to zero first.'
        ]);
        exit;
    }
    
    // 4. Delete in correct order (due to foreign key constraints)
    // a. First delete any purchase lines for this product's batches
    $sql_delete_purchase_lines = "DELETE pl FROM purchase_lines pl 
                                  JOIN product_batches pb ON pl.batch_id = pb.id 
                                  WHERE pb.product_id = ?";
    $stmt = $pdo->prepare($sql_delete_purchase_lines);
    $stmt->execute([$product_id]);
    
    // b. Delete any inventory movements for this product
    $sql_delete_movements = "DELETE FROM inventory_movements WHERE product_id = ?";
    $stmt = $pdo->prepare($sql_delete_movements);
    $stmt->execute([$product_id]);
    
    // c. Delete product batches
    $sql_delete_batches = "DELETE FROM product_batches WHERE product_id = ?";
    $stmt = $pdo->prepare($sql_delete_batches);
    $stmt->execute([$product_id]);
    
    // d. Finally delete the product
    $sql_delete_product = "DELETE FROM products WHERE id = ?";
    $stmt = $pdo->prepare($sql_delete_product);
    $stmt->execute([$product_id]);
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode([
        'status' => 'success', 
        'message' => 'Product "' . htmlspecialchars($product['name']) . '" deleted successfully'
    ]);
    
} catch (PDOException $e) {
    // Rollback on error
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Delete Product Error: " . $e->getMessage());
    echo json_encode([
        'status' => 'error', 
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    error_log("Delete Product Error: " . $e->getMessage());
    echo json_encode([
        'status' => 'error', 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>