<?php
include '../db.php';
include '../auth.php';

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

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

// Get POST data
$void_reason_id = $_POST['void_reason_id'] ?? null;
$notes = $_POST['notes'] ?? '';
$cart_total = $_POST['cart_total'] ?? 0;
$unhold_order_id = $_POST['unhold_order_id'] ?? null;

// Validate required fields
if (!$void_reason_id) {
    echo json_encode(['status' => 'error', 'message' => 'Void reason is required']);
    exit;
}

// Validate void reason exists and is active
$stmt = $conn->prepare("SELECT id, reason_name FROM void_reasons WHERE id = ? AND is_active = 1");
$stmt->bind_param("i", $void_reason_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid void reason']);
    exit;
}

$void_reason = $result->fetch_assoc();

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Create a new sale record for the voided order
    $invoice_number = 'INV' . time() . rand(1000, 9999);
    $sale_date = date('Y-m-d H:i:s');
    $customer_name = 'Walk-in Customer';
    $total_amount = $cart_total;
    $net_amount = $cart_total;
    
    // Insert sale record
    $stmt = $conn->prepare("INSERT INTO sales (invoice_number, sale_date, customer_name, total_amount, net_amount, payment_method, shift_id, order_taker_id) VALUES (?, ?, ?, ?, ?, 'void', ?, ?)");
    $shift_id = $_SESSION['shift_id'] ?? null;
    $user_id = $_SESSION['user_id'];
    $stmt->bind_param("sssddii", $invoice_number, $sale_date, $customer_name, $total_amount, $net_amount, $shift_id, $user_id);
    $stmt->execute();
    
    $sale_id = $conn->insert_id;
    
    // Create void order record
    $stmt = $conn->prepare("INSERT INTO void_orders (sale_id, void_reason_id, voided_by, notes, original_amount) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("iiisd", $sale_id, $void_reason_id, $user_id, $notes, $total_amount);
    $stmt->execute();
    
    $void_id = $conn->insert_id;
    
    // Update sale record with void_id
    $stmt = $conn->prepare("UPDATE sales SET void_id = ? WHERE id = ?");
    $stmt->bind_param("ii", $void_id, $sale_id);
    $stmt->execute();
    
    // If this was a resumed hold order, delete it from hold_orders and update table status
    if ($unhold_order_id) {
        // Get table_id from hold order before deleting
        $stmt = $conn->prepare("SELECT table_id FROM hold_orders WHERE id = ?");
        $stmt->bind_param("i", $unhold_order_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $hold_order = $result->fetch_assoc();
        $table_id = $hold_order['table_id'] ?? null;
        $stmt->close();
        
        // Update KDS order status to cancelled if it exists
        $stmt = $conn->prepare("SELECT id FROM kds_orders WHERE hold_id = ?");
        $stmt->bind_param("i", $unhold_order_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $kds_order = $result->fetch_assoc();
        $stmt->close();
        
        if ($kds_order) {
            // Update KDS order status to cancelled
            $cancellation_note = "CANCELLED: " . $void_reason['reason_name'];
            if (!empty($notes)) {
                $cancellation_note .= " - " . $notes;
            }
            
            $stmt = $conn->prepare("UPDATE kds_orders SET order_status = 'cancelled', notes = ?, updated_at = NOW() WHERE id = ?");
            $stmt->bind_param("si", $cancellation_note, $kds_order['id']);
            $stmt->execute();
            $stmt->close();
            
            // Update KDS order items status to cancelled
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'cancelled' WHERE kds_order_id = ?");
            $stmt->bind_param("i", $kds_order['id']);
            $stmt->execute();
            $stmt->close();
        }
        
        // Mark hold items as void instead of deleting them (for proper void reporting)
        $stmt = $conn->prepare("UPDATE hold_items SET void_status = 'void' WHERE hold_id = ?");
        $stmt->bind_param("i", $unhold_order_id);
        $stmt->execute();
        $stmt->close();
        
        // Delete hold order
        $stmt = $conn->prepare("DELETE FROM hold_orders WHERE id = ?");
        $stmt->bind_param("i", $unhold_order_id);
        $stmt->execute();
        $stmt->close();
        
        // Update table status if it was a dine-in order with a table
        if ($table_id) {
            // Check if there are other hold orders for this table
            $stmt = $conn->prepare("SELECT COUNT(*) as order_count FROM hold_orders WHERE table_id = ?");
            $stmt->bind_param("i", $table_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $check_data = $result->fetch_assoc();
            $stmt->close();
            
            // If no other hold orders for this table, mark it as available
            if ($check_data['order_count'] == 0) {
                $stmt = $conn->prepare("UPDATE dinein_tables SET status = 'available' WHERE id = ?");
                $stmt->bind_param("i", $table_id);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Order voided successfully',
        'sale_id' => $sale_id,
        'void_id' => $void_id,
        'unhold_order_id' => $unhold_order_id
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    error_log("Void sale error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Failed to void order. Please try again.']);
}
?>
