<?php
// Suppress errors for clean JSON output
define('SUPPRESS_ERRORS', true);

// Start output buffering to catch any unwanted output
ob_start();

session_start();

// Use the standard config file for database connection
require_once('../../includes/config.php');

// Clean buffer
ob_end_clean();

// Start fresh buffer for JSON
ob_start();

// Set headers
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

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

// Check database connection
if (!$con) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    ob_end_flush();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

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

if (!$data) {
    // Debug: show what was received
    $rawInput = file_get_contents('php://input');
    echo json_encode([
        'success' => false, 
        'message' => 'Invalid JSON data',
        'debug' => 'Received: ' . substr($rawInput, 0, 200)
    ]);
    exit();
}

$supplierId = isset($data['supplierId']) ? intval($data['supplierId']) : 0;
$paymentDate = isset($data['paymentDate']) ? $data['paymentDate'] : date('Y-m-d');
$paymentReference = isset($data['paymentReference']) ? trim($data['paymentReference']) : '';
$paymentNotes = isset($data['paymentNotes']) ? trim($data['paymentNotes']) : '';
$payments = isset($data['payments']) ? $data['payments'] : [];
$userId = intval($_SESSION['uid']);

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

if (empty($payments)) {
    echo json_encode(['success' => false, 'message' => 'No payment details provided']);
    exit();
}

// Validate payment date
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $paymentDate)) {
    echo json_encode(['success' => false, 'message' => 'Invalid payment date format']);
    ob_end_flush();
    exit();
}

@mysqli_begin_transaction($con);

try {
    $totalPaymentAmount = 0;
    $successCount = 0;

    foreach ($payments as $payment) {
        $invoiceId = isset($payment['invoiceId']) ? intval($payment['invoiceId']) : 0;
        $paymentAmount = isset($payment['paymentAmount']) ? floatval($payment['paymentAmount']) : 0;
        $paymentMode = isset($payment['paymentMode']) ? trim($payment['paymentMode']) : 'Cash';

        if ($invoiceId <= 0 || $paymentAmount <= 0) {
            continue;
        }

        // Verify invoice exists and belongs to supplier
        $verifyQuery = "SELECT ID, FinalAmount FROM tblpurchases WHERE ID = ? AND SupplierID = ?";
        $verifyStmt = @mysqli_prepare($con, $verifyQuery);
        
        if (!$verifyStmt) {
            throw new Exception('Failed to prepare verification query: ' . mysqli_error($con));
        }
        
        mysqli_stmt_bind_param($verifyStmt, 'ii', $invoiceId, $supplierId);
        mysqli_stmt_execute($verifyStmt);
        $verifyResult = mysqli_stmt_get_result($verifyStmt);
        
        if (mysqli_num_rows($verifyResult) === 0) {
            mysqli_stmt_close($verifyStmt);
            continue; // Skip invalid invoice
        }
        
        $invoiceRow = mysqli_fetch_assoc($verifyResult);
        $invoiceNumber = '';
        
        // Get invoice number for the payment reference
        $invQuery = "SELECT InvoiceNumber FROM tblpurchases WHERE ID = ?";
        $invStmt = mysqli_prepare($con, $invQuery);
        mysqli_stmt_bind_param($invStmt, 'i', $invoiceId);
        mysqli_stmt_execute($invStmt);
        $invResult = mysqli_stmt_get_result($invStmt);
        if ($invRow = mysqli_fetch_assoc($invResult)) {
            $invoiceNumber = $invRow['InvoiceNumber'];
        }
        mysqli_stmt_close($invStmt);
        mysqli_stmt_close($verifyStmt);

        // Insert payment as Debit entry in tblsupplier_accounts (we are paying the supplier)
        $paymentRef = 'PAY-' . $invoiceNumber . '-' . time();
        $description = 'Payment for Purchase Invoice ' . $invoiceNumber;
        
        $insertQuery = "
            INSERT INTO tblsupplier_accounts (
                SupplierID,
                InvoiceNumber,
                TransactionType,
                TransactionDate,
                Amount,
                BalanceAmount,
                Description,
                PaymentMode,
                ReferenceNumber,
                AddedBy
            ) VALUES (?, ?, 'Debit', ?, ?, ?, ?, ?, ?, ?)
        ";

        $insertStmt = @mysqli_prepare($con, $insertQuery);
        
        if (!$insertStmt) {
            throw new Exception('Failed to prepare insert query: ' . mysqli_error($con));
        }
        
        // Ensure all variables are properly set
        $refVal = $paymentReference ? $paymentReference : '';
        
        mysqli_stmt_bind_param(
            $insertStmt,
            'issddsssi',
            $supplierId,
            $paymentRef,
            $paymentDate,
            $paymentAmount,
            $paymentAmount,
            $description,
            $paymentMode,
            $refVal,
            $userId
        );

        if (!mysqli_stmt_execute($insertStmt)) {
            $error = mysqli_stmt_error($insertStmt);
            mysqli_stmt_close($insertStmt);
            throw new Exception('Failed to execute insert: ' . $error);
        }
        
        mysqli_stmt_close($insertStmt);
        
        // Update tblpurchases: increment PaymentAmount and update PaymentStatus
        $updatePurchaseQuery = "
            UPDATE tblpurchases 
            SET PaymentAmount = PaymentAmount + ?,
                PaymentStatus = CASE
                    WHEN (PaymentAmount + ?) >= FinalAmount THEN 'Paid'
                    WHEN (PaymentAmount + ?) > 0 THEN 'Partial'
                    ELSE 'Unpaid'
                END
            WHERE ID = ?
        ";
        $updatePurchaseStmt = mysqli_prepare($con, $updatePurchaseQuery);
        mysqli_stmt_bind_param($updatePurchaseStmt, 'dddi', $paymentAmount, $paymentAmount, $paymentAmount, $invoiceId);
        
        if (!mysqli_stmt_execute($updatePurchaseStmt)) {
            throw new Exception('Failed to update purchase record: ' . mysqli_stmt_error($updatePurchaseStmt));
        }
        
        mysqli_stmt_close($updatePurchaseStmt);
        
        $totalPaymentAmount += $paymentAmount;
        $successCount++;
    }

    if ($successCount === 0) {
        throw new Exception('No payments were recorded');
    }

    // Update supplier's outstanding balance (reduce by payment amount since we paid them)
    $updateSupplierQuery = "
        UPDATE tblsuppliers 
        SET OutstandingBalance = OutstandingBalance - ? 
        WHERE ID = ?
    ";
    $updateStmt = mysqli_prepare($con, $updateSupplierQuery);
    mysqli_stmt_bind_param($updateStmt, 'di', $totalPaymentAmount, $supplierId);
    mysqli_stmt_execute($updateStmt);
    mysqli_stmt_close($updateStmt);

    mysqli_commit($con);

    echo json_encode([
        'success' => true,
        'message' => 'Payment registered successfully',
        'paymentsRecorded' => $successCount,
        'totalAmount' => $totalPaymentAmount
    ]);

} catch (Exception $e) {
    mysqli_rollback($con);
    echo json_encode([
        'success' => false,
        'message' => 'Error saving payment: ' . $e->getMessage()
    ]);
}

// Flush the output buffer and end
ob_end_flush();
?>
