<?php
// modules/sales/ajax_delete_sale.php - SIMPLIFIED VERSION
session_start();
require_once '../assets/db_connect.php';

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

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';

// Check authentication
if ($shop_id == 0 || $user_id == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired']);
    exit;
}

// Check permissions
if ($user_role !== 'admin' && $user_role !== 'pharmacist') {
    echo json_encode(['status' => 'error', 'message' => 'Permission denied']);
    exit;
}

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

if (!$sale_id) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid sale ID']);
    exit;
}

try {
    // Get sale info
    $check_sql = "SELECT * FROM sales WHERE id = ? AND shop_id = ?";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$sale_id, $shop_id]);
    $sale = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sale) {
        echo json_encode(['status' => 'error', 'message' => 'Sale not found']);
        exit;
    }
    
    // Check if sale has payments
    if ($sale['paid'] > 0) {
        echo json_encode(['status' => 'error', 'message' => 'Cannot cancel sale with payments']);
        exit;
    }
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Get sale lines and return stock
    $lines_sql = "SELECT * FROM sale_lines WHERE sale_id = ?";
    $lines_stmt = $pdo->prepare($lines_sql);
    $lines_stmt->execute([$sale_id]);
    
    while ($line = $lines_stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($line['batch_id']) {
            // Return stock via adjustment
            $adj_sql = "INSERT INTO inventory_movements 
                       (product_id, batch_id, change_qty, movement_type, note, created_by, shop_id)
                       VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?)";
            
            $note = "Sale #{$sale['invoice_no']} cancelled - stock returned";
            
            $adj_stmt = $pdo->prepare($adj_sql);
            $adj_stmt->execute([
                $line['product_id'],
                $line['batch_id'],
                $line['qty'],
                $note,
                $user_id,
                $shop_id
            ]);
        }
    }
    
    // Update sale status to cancelled
    $update_sql = "UPDATE sales SET status = 'cancelled' WHERE id = ?";
    $update_stmt = $pdo->prepare($update_sql);
    $update_stmt->execute([$sale_id]);
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Sale cancelled successfully. Stock returned to inventory.'
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>