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

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header("Location: ../auth/login.php");
    exit;
}

$sale_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($sale_id <= 0) {
    header("Location: dashboard.php");
    exit;
}

try {
    $pdo->beginTransaction();
    
    // Get sale details
    $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
    $stmt->execute([$sale_id]);
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sale) {
        throw new Exception("Sale not found.");
    }
    
    // Check if sale is already cancelled or paid
    if ($sale['status'] === 'cancelled') {
        throw new Exception("Sale is already cancelled.");
    }
    
    if ($sale['paid'] > 0) {
        throw new Exception("Cannot cancel a sale with payments. Refund payments first.");
    }
    
    // Get sale items to return stock
    $stmt = $pdo->prepare("SELECT * FROM sale_lines WHERE sale_id = ?");
    $stmt->execute([$sale_id]);
    $sale_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Return stock for each item
    foreach ($sale_items as $item) {
        // Create reverse inventory movement
        $stmt = $pdo->prepare("INSERT INTO inventory_movements 
                              (product_id, batch_id, change_qty, movement_type, reference_id, note, created_by, shop_id)
                              VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?, ?)");
        $stmt->execute([
            $item['product_id'],
            $item['batch_id'],
            $item['qty'], // Positive qty to add back to stock
            $sale_id,
            "Sale #" . $sale_id . " cancellation",
            $_SESSION['user']['id'],
            $sale['shop_id']
        ]);
    }
    
    // Update sale status
    $stmt = $pdo->prepare("UPDATE sales SET status = 'cancelled' WHERE id = ?");
    $stmt->execute([$sale_id]);
    
    $pdo->commit();
    
    // Redirect with success message
    header("Location: sales_view.php?id=$sale_id&success=" . urlencode("Sale cancelled successfully. Stock returned to inventory."));
    
} catch (Exception $e) {
    $pdo->rollBack();
    header("Location: sales_view.php?id=$sale_id&error=" . urlencode("Error: " . $e->getMessage()));
}
exit;