<?php
/**
 * Save Shipping Details API
 * Saves or updates shipping address and purchase order details for an invoice
 */

session_start();
include_once('../../includes/config.php');

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

// Get POST data
$invoiceNumber = isset($_POST['invoice_number']) ? trim($_POST['invoice_number']) : '';
$customerId = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
$shippingAddress = isset($_POST['shipping_address']) ? trim($_POST['shipping_address']) : '';
$shippingCity = isset($_POST['shipping_city']) ? trim($_POST['shipping_city']) : '';
$shippingState = isset($_POST['shipping_state']) ? trim($_POST['shipping_state']) : '';
$shippingPinCode = isset($_POST['shipping_pincode']) ? trim($_POST['shipping_pincode']) : '';
$purchaseOrderNo = isset($_POST['purchase_order_no']) ? trim($_POST['purchase_order_no']) : '';
$purchaseOrderDate = isset($_POST['purchase_order_date']) ? trim($_POST['purchase_order_date']) : null;
$transportAmount = isset($_POST['transport_amount']) ? floatval($_POST['transport_amount']) : 0;
$transportName = isset($_POST['transport_name']) ? trim($_POST['transport_name']) : '';
$vehicleNumber = isset($_POST['vehicle_number']) ? trim($_POST['vehicle_number']) : '';
$transportGSTPercent = isset($_POST['transport_gst_percent']) ? floatval($_POST['transport_gst_percent']) : 0;
$transportGSTType = isset($_POST['transport_gst_type']) ? trim($_POST['transport_gst_type']) : 'inclusive';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

// Validate invoice number
if (empty($invoiceNumber)) {
    echo json_encode(['success' => false, 'message' => 'Invoice number is required']);
    exit();
}

// Prepare SQL query
// Check if record exists in tblsales
$checkQuery = "SELECT ID FROM tblsales WHERE InvoiceNumber = ?";
$checkStmt = mysqli_prepare($con, $checkQuery);
mysqli_stmt_bind_param($checkStmt, "s", $invoiceNumber);
mysqli_stmt_execute($checkStmt);
$checkResult = mysqli_stmt_get_result($checkStmt);

if (mysqli_num_rows($checkResult) > 0) {
    // Update existing record
    $updateQuery = "UPDATE tblsales 
                    SET ShippingAddress = ?, 
                        ShippingCity = ?, 
                        ShippingState = ?, 
                        ShippingPinCode = ?, 
                        PurchaseOrderNo = ?, 
                        PurchaseOrderDate = ?,
                        Cooli = ?,
                        TransportName = ?,
                        VehicleNumber = ?,
                        TransportGSTPercent = ?,
                        TransportGSTType = ?,
                        Notes = ?
                    WHERE InvoiceNumber = ?";
    
    $updateStmt = mysqli_prepare($con, $updateQuery);
    mysqli_stmt_bind_param($updateStmt, "ssssssdssdsss", 
        $shippingAddress, 
        $shippingCity, 
        $shippingState, 
        $shippingPinCode, 
        $purchaseOrderNo, 
        $purchaseOrderDate,
        $transportAmount,
        $transportName,
        $vehicleNumber,
        $transportGSTPercent,
        $transportGSTType,
        $notes,
        $invoiceNumber
    );
    
    if (mysqli_stmt_execute($updateStmt)) {
        echo json_encode([
            'success' => true, 
            'message' => 'Shipping details updated successfully',
            'data' => [
                'invoice_number' => $invoiceNumber,
                'shipping_address' => $shippingAddress,
                'shipping_city' => $shippingCity,
                'shipping_state' => $shippingState,
                'shipping_pincode' => $shippingPinCode,
                'purchase_order_no' => $purchaseOrderNo,
                'purchase_order_date' => $purchaseOrderDate,
                'transport_amount' => $transportAmount,
                'transport_name' => $transportName,
                'vehicle_number' => $vehicleNumber,
                'transport_gst_percent' => $transportGSTPercent,
                'transport_gst_type' => $transportGSTType,
                'notes' => $notes
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'Error updating shipping details: ' . mysqli_error($con)
        ]);
    }
    
    mysqli_stmt_close($updateStmt);
} else {
    // If invoice doesn't exist yet, we'll store temporarily and update when invoice is saved
    // For now, return success with a note
    echo json_encode([
        'success' => true, 
        'message' => 'Shipping details will be saved with invoice',
        'pending' => true,
        'data' => [
            'invoice_number' => $invoiceNumber,
            'shipping_address' => $shippingAddress,
            'shipping_city' => $shippingCity,
            'shipping_state' => $shippingState,
            'shipping_pincode' => $shippingPinCode,
            'purchase_order_no' => $purchaseOrderNo,
            'purchase_order_date' => $purchaseOrderDate,
            'transport_amount' => $transportAmount,
            'transport_name' => $transportName,
            'vehicle_number' => $vehicleNumber,
            'transport_gst_percent' => $transportGSTPercent,
            'transport_gst_type' => $transportGSTType,
            'notes' => $notes
        ]
    ]);
}

mysqli_stmt_close($checkStmt);
mysqli_close($con);
?>
