<?php
session_start();
require_once '../assets/db_connect.php';

// Ensure user logged in
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

$user = $_SESSION['user'];
$user_id = $user['id'] ?? 1;

// Get purchase ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: list_purchases.php?error=Invalid purchase ID");
    exit;
}

$purchase_id = intval($_GET['id']);

try {
    // Start transaction
    $pdo->beginTransaction();
    
    // 1. Check if purchase exists and get details
    $check_sql = "SELECT p.*, s.name as supplier_name 
                  FROM purchases p 
                  LEFT JOIN suppliers s ON p.supplier_id = s.id 
                  WHERE p.id = ?";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$purchase_id]);
    $purchase = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$purchase) {
        $pdo->rollBack();
        header("Location: list_purchases.php?error=Purchase not found");
        exit;
    }
    
    // 2. Check if any batches from this purchase have been sold
    $sold_check_sql = "SELECT COUNT(*) as sold_count 
                       FROM purchase_lines pl 
                       JOIN sale_lines sl ON pl.batch_id = sl.batch_id 
                       WHERE pl.purchase_id = ?";
    $sold_check_stmt = $pdo->prepare($sold_check_sql);
    $sold_check_stmt->execute([$purchase_id]);
    $sold_check = $sold_check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($sold_check['sold_count'] > 0) {
        $pdo->rollBack();
        header("Location: list_purchases.php?error=Cannot delete purchase. Some items have been sold.");
        exit;
    }
    
    // 3. Get all batch IDs from this purchase
    $batch_sql = "SELECT batch_id FROM purchase_lines WHERE purchase_id = ?";
    $batch_stmt = $pdo->prepare($batch_sql);
    $batch_stmt->execute([$purchase_id]);
    $batch_ids = $batch_stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // 4. Delete inventory movements for these batches
    if (!empty($batch_ids)) {
        $placeholders = implode(',', array_fill(0, count($batch_ids), '?'));
        $delete_movements_sql = "DELETE FROM inventory_movements 
                                WHERE batch_id IN ($placeholders) 
                                AND movement_type = 'PURCHASE' 
                                AND reference_id = ?";
        $movement_params = array_merge($batch_ids, [$purchase_id]);
        $delete_movements_stmt = $pdo->prepare($delete_movements_sql);
        $delete_movements_stmt->execute($movement_params);
    }
    
    // 5. Delete purchase lines
    $delete_lines_sql = "DELETE FROM purchase_lines WHERE purchase_id = ?";
    $delete_lines_stmt = $pdo->prepare($delete_lines_sql);
    $delete_lines_stmt->execute([$purchase_id]);
    
    // 6. Delete purchase
    $delete_purchase_sql = "DELETE FROM purchases WHERE id = ?";
    $delete_purchase_stmt = $pdo->prepare($delete_purchase_sql);
    $delete_purchase_stmt->execute([$purchase_id]);
    
    // 7. Update batch quantities (set to 0 since purchase is deleted)
    if (!empty($batch_ids)) {
        $update_batch_sql = "UPDATE product_batches SET qty = 0 WHERE id IN (" . 
                           implode(',', array_fill(0, count($batch_ids), '?')) . ")";
        $update_batch_stmt = $pdo->prepare($update_batch_sql);
        $update_batch_stmt->execute($batch_ids);
    }
    
    // Commit transaction
    $pdo->commit();
    
    // Log the deletion
    error_log("Purchase #$purchase_id deleted by user #$user_id. Invoice: " . $purchase['invoice_no']);
    
    // Redirect with success message
    header("Location: list_purchases.php?deleted=1");
    exit;
    
} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    error_log("Error deleting purchase #$purchase_id: " . $e->getMessage());
    header("Location: list_purchases.php?error=Database error: " . urlencode($e->getMessage()));
    exit;
}