<?php
/**
 * Get Shipping Details API
 * Retrieves 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']) : '';

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

// Query to get shipping details
$query = "SELECT 
            ShippingAddress, 
            ShippingCity, 
            ShippingState, 
            ShippingPinCode, 
            PurchaseOrderNo, 
            PurchaseOrderDate,
            Cooli as TransportAmount,
            TransportName,
            VehicleNumber,
            TransportGSTPercent,
            TransportGSTType,
            Notes
          FROM tblsales 
          WHERE InvoiceNumber = ?";

$stmt = mysqli_prepare($con, $query);
mysqli_stmt_bind_param($stmt, "s", $invoiceNumber);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) > 0) {
    $data = mysqli_fetch_assoc($result);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'ShippingAddress' => $data['ShippingAddress'] ?? '',
            'ShippingCity' => $data['ShippingCity'] ?? '',
            'ShippingState' => $data['ShippingState'] ?? '',
            'ShippingPinCode' => $data['ShippingPinCode'] ?? '',
            'PurchaseOrderNo' => $data['PurchaseOrderNo'] ?? '',
            'PurchaseOrderDate' => $data['PurchaseOrderDate'] ?? '',
            'TransportAmount' => $data['TransportAmount'] ?? 0,
            'TransportName' => $data['TransportName'] ?? '',
            'VehicleNumber' => $data['VehicleNumber'] ?? '',
            'TransportGSTPercent' => $data['TransportGSTPercent'] ?? 0,
            'TransportGSTType' => $data['TransportGSTType'] ?? 'inclusive',
            'Notes' => $data['Notes'] ?? ''
        ]
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'No shipping details found for this invoice',
        'data' => null
    ]);
}

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