<?php
session_start();
header('Content-Type: application/json');
include_once('../../includes/config.php');

// Check authentication
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$response = ['success' => false, 'message' => ''];

// Get purchase ID
$purchaseId = isset($_POST['purchaseId']) ? intval($_POST['purchaseId']) : 0;

if ($purchaseId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid purchase ID']);
    exit();
}

try {
    // Start transaction
    mysqli_begin_transaction($con);
    
    // Get purchase details before deletion
    $purchaseQuery = "SELECT p.*, s.SupplierName 
                      FROM tblpurchases p 
                      LEFT JOIN tblsuppliers s ON p.SupplierID = s.ID 
                      WHERE p.ID = $purchaseId";
    $purchaseResult = mysqli_query($con, $purchaseQuery);
    
    if (!$purchaseResult || mysqli_num_rows($purchaseResult) == 0) {
        throw new Exception('Purchase not found');
    }
    
    $purchase = mysqli_fetch_assoc($purchaseResult);
    $supplierId = $purchase['SupplierID'];
    $invoiceNumber = $purchase['InvoiceNumber'];
    $purchaseType = $purchase['PurchaseType'];
    $finalAmount = floatval($purchase['FinalAmount']);
    $paymentAmount = isset($purchase['PaymentAmount']) ? floatval($purchase['PaymentAmount']) : 0;
    
    // Detect if this is a PURCHASE RETURN
    $isReturn = (strpos($purchaseType, '-PURCHASE-RETURN') !== false);
    
    // Get purchase details to reverse stock
    $detailsQuery = "SELECT ProductID, Quantity FROM tblpurchases_details WHERE PurchaseID = $purchaseId";
    $detailsResult = mysqli_query($con, $detailsQuery);
    
    if (!$detailsResult) {
        throw new Exception('Error fetching purchase details: ' . mysqli_error($con));
    }
    
    // *** IMPORTANT: Reverse stock based on purchase type ***
    while ($detail = mysqli_fetch_assoc($detailsResult)) {
        $productId = intval($detail['ProductID']);
        $quantity = floatval($detail['Quantity']);
        
        if ($productId > 0 && $quantity > 0) {
            // For PURCHASE deletion: DECREASE stock (reverse the purchase - goods go out)
            // For RETURN deletion: INCREASE stock (reverse the return - goods come back)
            $stockOperation = $isReturn ? '+' : '-';
            $updateStockSql = "UPDATE tblitems 
                              SET CurrentStock = CurrentStock $stockOperation $quantity 
                              WHERE ID = $productId";
            
            if (!mysqli_query($con, $updateStockSql)) {
                throw new Exception('Error updating stock for product ID ' . $productId . ': ' . mysqli_error($con));
            }
        }
    }
    
    // Delete purchase details
    $deleteDetailsSql = "DELETE FROM tblpurchases_details WHERE PurchaseID = $purchaseId";
    if (!mysqli_query($con, $deleteDetailsSql)) {
        throw new Exception('Error deleting purchase details: ' . mysqli_error($con));
    }
    
    // Delete GST details if exists
    $deleteGSTSql = "DELETE FROM tblpurchases_gst_details WHERE PurchaseID = $purchaseId";
    mysqli_query($con, $deleteGSTSql);
    
    // Delete supplier account entries (both purchase entry and payment if any)
    // Delete main purchase entry (Credit - we owe supplier)
    $deleteAccountSql = "DELETE FROM tblsupplier_accounts 
                         WHERE InvoiceNumber = '$invoiceNumber' AND SupplierID = $supplierId";
    if (!mysqli_query($con, $deleteAccountSql)) {
        throw new Exception('Error deleting supplier account: ' . mysqli_error($con));
    }
    
    // Delete payment entry if exists (Debit - we paid supplier)
    $paymentRef = 'PAY-' . $invoiceNumber;
    $deletePaymentSql = "DELETE FROM tblsupplier_accounts 
                         WHERE InvoiceNumber = '$paymentRef' AND SupplierID = $supplierId";
    mysqli_query($con, $deletePaymentSql); // Don't throw error if no payment exists
    
    // Update supplier's outstanding balance
    // Reverse the purchase/return entry and payment entry
    // For PURCHASE deletion: 
    //   - Remove Credit (reduce what we owe): -$finalAmount
    //   - Remove Debit (reverse payment made): +$paymentAmount
    //   - Net effect: -$finalAmount + $paymentAmount
    // For RETURN deletion:
    //   - Remove Debit (reduce what they owe us): +$finalAmount
    //   - Remove Credit (reverse refund received): -$paymentAmount
    //   - Net effect: +$finalAmount - $paymentAmount
    if ($isReturn) {
        $balanceAdjustment = $finalAmount - $paymentAmount;
    } else {
        $balanceAdjustment = -$finalAmount + $paymentAmount;
    }
    
    $updateSupplierBalanceSql = "UPDATE tblsuppliers 
                                 SET OutstandingBalance = OutstandingBalance + $balanceAdjustment 
                                 WHERE ID = $supplierId";
    
    if (!mysqli_query($con, $updateSupplierBalanceSql)) {
        throw new Exception('Error updating supplier balance: ' . mysqli_error($con));
    }
    
    // Delete purchase master record
    $deletePurchaseSql = "DELETE FROM tblpurchases WHERE ID = $purchaseId";
    if (!mysqli_query($con, $deletePurchaseSql)) {
        throw new Exception('Error deleting purchase: ' . mysqli_error($con));
    }
    
    // Commit transaction
    mysqli_commit($con);
    
    $response['success'] = true;
    $response['message'] = 'Purchase deleted successfully';
    $response['invoiceNumber'] = $invoiceNumber;
    $response['details'] = [
        'purchaseId' => $purchaseId,
        'supplierId' => $supplierId,
        'finalAmount' => $finalAmount,
        'stockReversed' => true
    ];
    
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($con);
    $response['message'] = 'Error: ' . $e->getMessage();
    $response['debug'] = [
        'purchaseId' => $purchaseId,
        'error' => $e->getMessage()
    ];
}

echo json_encode($response);
?>
