<?php
// Prevent any output before headers and force JSON-safe error handling
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0); // Avoid HTML error output; we'll return JSON instead

// Emit JSON errors instead of HTML
function json_error_response($message, $httpCode = 500) {
    if (!headers_sent()) {
        http_response_code($httpCode);
        header('Content-Type: application/json');
    }
    echo json_encode(['success' => false, 'message' => $message]);
}

set_error_handler(function ($severity, $message, $file, $line) {
    // Convert all errors to exceptions so we can handle uniformly
    throw new ErrorException($message, 0, $severity, $file, $line);
});

register_shutdown_function(function () {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        // Clean any output and return JSON for fatal errors
        while (ob_get_level() > 0) { ob_end_clean(); }
        json_error_response('Server error: ' . $error['message'] . ' at ' . basename($error['file']) . ':' . $error['line']);
    }
});

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

// Clean any output that might have been generated
ob_clean();
header('Content-Type: application/json');

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

    $userId = $_SESSION['uid'];

    // Only allow POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        exit();
    }

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON input: ' . json_last_error_msg()]);
        exit();
    }

    // Validate required fields
    if (!isset($input['customer_id']) || !isset($input['amount']) || !isset($input['payment_method']) || !isset($input['payment_date'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }

    $customerId = intval($input['customer_id']);
    $transactionType = isset($input['transaction_type']) ? mysqli_real_escape_string($con, $input['transaction_type']) : 'Credit';
    $amount = floatval($input['amount']);
    $paymentMethod = mysqli_real_escape_string($con, $input['payment_method']);
    $paymentDate = mysqli_real_escape_string($con, $input['payment_date']);
    $referenceNumber = isset($input['reference_number']) ? mysqli_real_escape_string($con, $input['reference_number']) : null;
    $description = isset($input['description']) ? mysqli_real_escape_string($con, $input['description']) : null;

    // Validate input values
    if ($customerId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
        exit();
    }

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

    // Validate payment method
    $validPaymentMethods = ['Cash', 'Bank Transfer', 'Cheque', 'UPI', 'Card', 'Online'];
    if (!in_array($paymentMethod, $validPaymentMethods)) {
        echo json_encode(['success' => false, 'message' => 'Invalid payment method']);
        exit();
    }

    // Validate transaction type
    $validTransactionTypes = ['Credit', 'Debit'];
    if (!in_array($transactionType, $validTransactionTypes)) {
        echo json_encode(['success' => false, 'message' => 'Invalid transaction type']);
        exit();
    }

    // Validate date format
    if (!DateTime::createFromFormat('Y-m-d', $paymentDate)) {
        echo json_encode(['success' => false, 'message' => 'Invalid payment date format']);
        exit();
    }

    // Check if customer exists
    $customerCheck = "SELECT ID, CustomerName FROM tblcustomers WHERE ID = ? AND IsActive = 1";
    $stmt = mysqli_prepare($con, $customerCheck);
    if (!$stmt) {
        throw new Exception('Failed to prepare customer check query: ' . mysqli_error($con));
    }
    
    mysqli_stmt_bind_param($stmt, "i", $customerId);
    mysqli_stmt_execute($stmt);
    $customerResult = mysqli_stmt_get_result($stmt);

    if (mysqli_num_rows($customerResult) === 0) {
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
        exit();
    }

    $customer = mysqli_fetch_assoc($customerResult);

    // Begin transaction
    mysqli_begin_transaction($con);
    
    // Insert payment record into tblcustomerpayments
    $insertPayment = "INSERT INTO tblcustomerpayments (
        CustomerID, 
        TransactionType, 
        Amount, 
        PaidAmount, 
        PaymentMethod, 
        ReferenceNumber, 
        TransactionDate, 
        Description, 
        Status, 
        CreatedBy, 
        IsActive
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Completed', ?, 1)";
    
    $stmt = mysqli_prepare($con, $insertPayment);
    if (!$stmt) {
        throw new Exception('Failed to prepare insert query: ' . mysqli_error($con));
    }
    // Bind: i (CustomerID), s (TransactionType), d (Amount), d (PaidAmount), s (PaymentMethod), s (ReferenceNumber), s (TransactionDate), s (Description), i (CreatedBy)
    mysqli_stmt_bind_param($stmt, "isddssssi",
        $customerId,
        $transactionType,
        $amount,
        $amount,
        $paymentMethod,
        $referenceNumber,
        $paymentDate,
        $description,
        $userId
    );
    
    if (!mysqli_stmt_execute($stmt)) {
        throw new Exception('Failed to insert payment record: ' . mysqli_stmt_error($stmt));
    }
    
    $paymentId = mysqli_insert_id($con);
    
    // Commit transaction
    mysqli_commit($con);
    
    // Return success response
    echo json_encode([
        'success' => true, 
        'message' => 'Payment recorded successfully',
        'payment_id' => $paymentId,
        'customer_name' => $customer['CustomerName'],
        'amount' => $amount,
        'payment_method' => $paymentMethod,
        'payment_date' => $paymentDate
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if (isset($con)) {
        mysqli_rollback($con);
    }
    
    error_log("Payment recording error: " . $e->getMessage());
    json_error_response('Failed to record payment: ' . $e->getMessage(), 500);
}

if (isset($con)) {
    mysqli_close($con);
}
?>
