<?php
// ajax/delete_batch.php - Use with caution!
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;
}

$batch_id = $_POST['batch_id'] ?? 0;
$confirmation = $_POST['confirmation'] ?? '';

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

try {
    // Get batch details for verification
    $stmt = $pdo->prepare("SELECT batch_no, is_active FROM product_batches WHERE id = ?");
    $stmt->execute([$batch_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        echo json_encode(['status' => 'error', 'message' => 'Batch not found']);
        exit;
    }
    
    // Verify confirmation matches batch number
    if ($confirmation !== $batch['batch_no']) {
        echo json_encode(['status' => 'error', 'message' => 'Confirmation failed. Batch numbers do not match.']);
        exit;
    }
    
    // Check if batch has been used in sales (prevent deletion if used)
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM sale_lines WHERE batch_id = ?");
    $stmt->execute([$batch_id]);
    $used_in_sales = $stmt->fetchColumn();
    
    if ($used_in_sales > 0) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Cannot delete batch that has been used in sales. Deactivate instead.'
        ]);
        exit;
    }
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Delete inventory movements for this batch
    $stmt = $pdo->prepare("DELETE FROM inventory_movements WHERE batch_id = ?");
    $stmt->execute([$batch_id]);
    
    // Delete purchase lines for this batch
    $stmt = $pdo->prepare("DELETE FROM purchase_lines WHERE batch_id = ?");
    $stmt->execute([$batch_id]);
    
    // Finally delete the batch
    $stmt = $pdo->prepare("DELETE FROM product_batches WHERE id = ?");
    $stmt->execute([$batch_id]);
    
    $pdo->commit();
    
    // Log the deletion
    $stmt = $pdo->prepare("INSERT INTO audit_log (user_id, action, details, created_at) 
                          VALUES (?, ?, ?, NOW())");
    $stmt->execute([
        $_SESSION['user']['id'],
        'BATCH_DELETE',
        "Batch #{$batch_id} ({$batch['batch_no']}) permanently deleted."
    ]);
    
    echo json_encode([
        'status' => 'success', 
        'message' => "Batch {$batch['batch_no']} has been permanently deleted"
    ]);
    
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    echo json_encode([
        'status' => 'error', 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>