<?php
// Disable output buffering and error display in JSON response
error_reporting(0);
ini_set('display_errors', 0);

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

// Include config
$configPath = '../../includes/config.php';
if (!file_exists($configPath)) {
    echo json_encode(['success' => false, 'message' => 'Config file not found']);
    exit();
}
include_once($configPath);

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access - Please login']);
    exit();
}

$userId = $_SESSION['uid'];

// Get POST data
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);

// Check for JSON decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode([
        'success' => false, 
        'message' => 'Invalid JSON: ' . json_last_error_msg(),
        'raw' => substr($rawInput, 0, 200)
    ]);
    exit();
}

if (!isset($data['items']) || empty($data['items'])) {
    echo json_encode(['success' => false, 'message' => 'No items in cart']);
    exit();
}

// Generate unique hold number
$holdNumber = 'HOLD-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

// Check if hold number already exists
$checkQuery = "SELECT ID FROM tblhold_bills WHERE HoldNumber = '$holdNumber'";
$checkResult = mysqli_query($con, $checkQuery);

// Check if query failed (table might not exist)
if ($checkResult === false) {
    echo json_encode([
        'success' => false, 
        'message' => 'Database error: ' . mysqli_error($con) . '. Please ensure the tblhold_bills table exists.',
        'setupUrl' => '../../database/setup_hold_bills_web.php'
    ]);
    exit();
}

if (mysqli_num_rows($checkResult) > 0) {
    // Generate new number
    $holdNumber = 'HOLD-' . date('YmdHis') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
}

// Prepare data
$customerID = isset($data['customerId']) && $data['customerId'] > 0 ? intval($data['customerId']) : 'NULL';
$customerName = isset($data['customerName']) ? mysqli_real_escape_string($con, $data['customerName']) : '';
$salesType = isset($data['salesType']) ? mysqli_real_escape_string($con, $data['salesType']) : 'GST';
$invoiceNumber = isset($data['invoiceNumber']) ? mysqli_real_escape_string($con, $data['invoiceNumber']) : '';

// Properly encode items as JSON - use JSON_UNESCAPED_UNICODE to handle special characters
$itemsJSON = json_encode($data['items'], JSON_UNESCAPED_UNICODE);
if ($itemsJSON === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to encode items: ' . json_last_error_msg()
    ]);
    exit();
}
// Escape for MySQL
$itemsJSON = mysqli_real_escape_string($con, $itemsJSON);

$subTotal = isset($data['subTotal']) ? floatval($data['subTotal']) : 0.00;
$taxAmount = isset($data['taxAmount']) ? floatval($data['taxAmount']) : 0.00;
$grandTotal = isset($data['grandTotal']) ? floatval($data['grandTotal']) : 0.00;
$discount = isset($data['discount']) ? floatval($data['discount']) : 0.00;
$roundOff = isset($data['roundOff']) ? floatval($data['roundOff']) : 0.00;
$totalItems = count($data['items']);
$notes = isset($data['notes']) ? mysqli_real_escape_string($con, $data['notes']) : '';

// Insert into database
$insertQuery = "INSERT INTO tblhold_bills 
    (HoldNumber, CustomerID, CustomerName, SalesType, InvoiceNumber, ItemsJSON, 
     SubTotal, TaxAmount, GrandTotal, Discount, RoundOff, TotalItems, HeldBy, Notes) 
    VALUES 
    ('$holdNumber', $customerID, '$customerName', '$salesType', '$invoiceNumber', '$itemsJSON', 
     $subTotal, $taxAmount, $grandTotal, $discount, $roundOff, $totalItems, $userId, '$notes')";

if (mysqli_query($con, $insertQuery)) {
    echo json_encode([
        'success' => true, 
        'message' => 'Bill held successfully',
        'holdNumber' => $holdNumber,
        'id' => mysqli_insert_id($con)
    ]);
} else {
    echo json_encode([
        'success' => false, 
        'message' => 'Failed to hold bill: ' . mysqli_error($con)
    ]);
}

mysqli_close($con);
?>
