<?php
session_start();
include '../../assets/constant/config.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://test.instamojo.com/api/1.1/payment-requests/');
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "X-Api-Key:",
        "X-Auth-Token:"
    ));
    $payload = array(
        'purpose' => $_POST['purpose'],
        'amount' => $_POST['amount'],
        'phone' => '9999999999',
        'buyer_name' => $_POST['name'],
        'redirect_url' => 'http://localhost/church/admin/redirect.php',
        'send_email' => true,
        'send_sms' => true,
        'email' => $_POST['email'],
        'allow_repeated_payments' => false
    );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
    $response = curl_exec($ch);
    curl_close($ch); 

    print_r($response);

    if ($response !== false) {
        $decoded_response = json_decode($response);

        if ($decoded_response !== null && isset($decoded_response->payment_request)) {
            $payment_request = $decoded_response->payment_request;
            $_SESSION['pid'] = $payment_request->id;

            $stmt = $conn->prepare("INSERT INTO instapayment (purpose, amount,name, email, payment_id) VALUES (:purpose, :amount, :buyer_name, :email, :payment_id)");
            $stmt->bindValue(':purpose', $_POST['purpose']);
            $stmt->bindValue(':amount', $_POST['amount']);
            
            $stmt->bindValue(':buyer_name', $_POST['name']);
            $stmt->bindValue(':email', $_POST['email']);
            $stmt->bindValue(':payment_id', $payment_request->id);

            if ($stmt->execute()) {
                header('location:' . $payment_request->longurl);
                exit(); // Stop further execution
            } else {
                echo "Error: " . implode(", ", $stmt->errorInfo());
            }
        } else {
            echo "Failed to decode Instamojo response.";
        }
    } else {
        echo "Failed to get response from Instamojo.";
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>