<?php
/**
 * API: Save GST Details for a Purchase
 * Saves detailed GST breakdown when a purchase is completed
 */

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

// Include database connection
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
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit();
}

$purchaseId = isset($data['saleId']) ? intval($data['saleId']) : 0;
$invoiceNumber = isset($data['invoiceNumber']) ? mysqli_real_escape_string($con, $data['invoiceNumber']) : '';
$taxType = isset($data['taxType']) ? mysqli_real_escape_string($con, $data['taxType']) : 'INTRA';
$gstItems = isset($data['gstItems']) ? $data['gstItems'] : [];

if ($purchaseId <= 0 || empty($invoiceNumber) || empty($gstItems)) {
    echo json_encode(['success' => false, 'message' => 'Missing required data']);
    exit();
}

try {
    // Start transaction
    mysqli_begin_transaction($con);
    
    // First, delete any existing GST details for this purchase
    $deleteQuery = "DELETE FROM tblpurchases_gst_details WHERE PurchaseID = $purchaseId";
    mysqli_query($con, $deleteQuery);
    
    // Insert new GST details
    $insertQuery = "INSERT INTO tblpurchases_gst_details 
        (PurchaseID, InvoiceNumber, ProductID, ProductCode, ProductName, HSNCode, Rate, Quantity, 
         DiscountAmount, TaxableAmount, TaxPercentage, TaxType, 
         CGSTPercent, CGSTAmount, SGSTPercent, SGSTAmount, 
         IGSTPercent, IGSTAmount, TotalTaxAmount, FinalAmount) 
        VALUES ";
    
    $values = [];
    foreach ($gstItems as $item) {
        $productId = intval($item['productId']);
        $productCode = mysqli_real_escape_string($con, $item['productCode']);
        $productName = mysqli_real_escape_string($con, $item['productName']);
        $hsnCode = isset($item['hsnCode']) ? mysqli_real_escape_string($con, $item['hsnCode']) : '';
        $rate = floatval($item['rate']);
        $quantity = floatval($item['quantity']);
        $discountAmount = floatval($item['discountAmount']);
        $taxableAmount = floatval($item['taxableAmount']);
        $taxPercentage = floatval($item['taxPercentage']);
        $cgstPercent = floatval($item['cgstPercent']);
        $cgstAmount = floatval($item['cgstAmount']);
        $sgstPercent = floatval($item['sgstPercent']);
        $sgstAmount = floatval($item['sgstAmount']);
        $igstPercent = floatval($item['igstPercent']);
        $igstAmount = floatval($item['igstAmount']);
        $totalTaxAmount = floatval($item['totalTaxAmount']);
        $finalAmount = floatval($item['finalAmount']);
        
        $hsnValue = !empty($hsnCode) ? "'$hsnCode'" : "NULL";
        
        $values[] = "($purchaseId, '$invoiceNumber', $productId, '$productCode', '$productName', $hsnValue,
                     $rate, $quantity, $discountAmount, $taxableAmount, $taxPercentage, '$taxType', 
                     $cgstPercent, $cgstAmount, $sgstPercent, $sgstAmount, 
                     $igstPercent, $igstAmount, $totalTaxAmount, $finalAmount)";
    }
    
    $insertQuery .= implode(', ', $values);
    
    if (!mysqli_query($con, $insertQuery)) {
        throw new Exception('Error saving GST details: ' . mysqli_error($con));
    }
    
    // Commit transaction
    mysqli_commit($con);
    
    echo json_encode([
        'success' => true, 
        'message' => 'GST details saved successfully',
        'recordsInserted' => count($gstItems)
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    mysqli_rollback($con);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($con);
?>
