<?php
  include('includes/config.php');
    include('includes/db.php');



$errors = [];

// Validation for required fields
if (!isset($_REQUEST['amount']) || empty($_REQUEST['amount']) || !is_numeric($_REQUEST['amount'])) {
    $errors[] = 'Amount is required and must be a numeric value.';
}

if (!isset($_REQUEST['cus_name']) || empty($_REQUEST['cus_name'])) {
    $errors[] = 'Customer name is required.';
}

if (!isset($_REQUEST['cus_email']) || empty($_REQUEST['cus_email']) || !filter_var($_REQUEST['cus_email'], FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Customer email is required and must be a valid email address.';
}

if (!isset($_REQUEST['cus_number']) || empty($_REQUEST['cus_number'])) {
    $errors[] = 'Customer number is required.';
}

if (!isset($_REQUEST['method_transaction_id']) || empty($_REQUEST['method_transaction_id'])) {
    $errors[] = 'Transaction ID is required.';
}

if (!isset($_REQUEST['status']) || empty($_REQUEST['status'])) {
    $errors[] = 'Status is required.';
}

if (isset($_REQUEST['extra']) && !is_array($_REQUEST['extra'])) {
    $errors[] = 'Extra field must be an array if provided.';
}

// If there are validation errors, return them and stop further processing
if (!empty($errors)) {
    echo json_encode(['errors' => $errors]);
    exit; 
}

// Check if payment status is 'Completed'
if ($_REQUEST['status'] == 'Completed') {

    try {
        $amount = $_REQUEST['amount'] ;
        // Set PDO error mode to exception for better error handling
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Prepare SQL to update balance
        $sql = "UPDATE users SET balance = balance + :amount WHERE email = :email";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':amount', $amount);
        $stmt->bindParam(':email', $_REQUEST['cus_number']);
        $stmt->execute();  // Execute balance update query

        // Prepare SQL to insert payment record
        $amountAdd = "INSERT INTO payment (paymentID, trxID, paymentExecuteTime, customerMsisdn, amount, email) 
                      VALUES (:paymentID, :trxID, :paymentExecuteTime, :customerMsisdn, :amount, :email)";
        $amountAddStmt = $dbh->prepare($amountAdd);

        // Generate a random customer MSISDN (phone number) if needed
        $customerMsisdn = rand(1000000000, 9999999999);  // Example random phone number

        // Insert payment data
        $amountAddStmt->bindParam(':paymentID', $_REQUEST['trx_id']);
        $amountAddStmt->bindParam(':trxID', $_REQUEST['method_transaction_id']);
        $amountAddStmt->bindParam(':paymentExecuteTime', date('Y-m-d H:i:s')); // Use current time
        $amountAddStmt->bindParam(':customerMsisdn', $customerMsisdn);
        $amountAddStmt->bindParam(':amount', $amount);
        $amountAddStmt->bindParam(':email', $_REQUEST['cus_number']);
        $amountAddStmt->execute();  // Execute payment insertion

        // Send success response
        echo 'Payment Success';
        exit;

    } catch (PDOException $e) {
        // Catch any PDO exceptions and return an error message
        $errors[] = 'Database error: ' . $e->getMessage();
        echo json_encode(['errors' => $errors]);
        exit;
    }

} else {
    // If payment status is not 'Completed'
    $errors[] = 'Payment status is ' . $_REQUEST['status'];
    echo json_encode(['errors' => $errors]);
    exit;
}
?>