<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
require_once "../config/db.php";

$data = json_decode(file_get_contents("php://input"), true) ?: [];

if (!isset($_SESSION['valid']) || $_SESSION['valid'] !== true || !isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Session expired. Please sign in again."]);
    exit();
}

$user_id = (int) $_SESSION['user_id'];
$usd = filter_var($data["usd"] ?? null, FILTER_VALIDATE_FLOAT);
$phone = preg_replace('/\D/', '', (string)($data["phone"] ?? ''));

if ($usd === false || $usd < 5 || !preg_match('/^254(7|1)\d{8}$/', $phone)) {
    http_response_code(422);
    echo json_encode(["status" => "error", "message" => "Minimum deposit is $5. Enter a valid Kenyan M-Pesa phone number."]);
    exit();
}

$rate = 129.1;
$kes = round($usd * $rate);

$shortcode = "4168553";
$passkey = "b53d140509cb2b0f51a5939375e857da6afa5071bfc5f1239e38c57d0a5f2bc5";
$consumerKey = "yrSfRYeKGqGXNlIu8W2OAdunskod36frZfKGoiKCSXVOJ5o2";
$consumerSecret = "pE4Blivbaflxp3r9xdBPoQYNllNO57JwhEKXq6vdGk89iOoaBKyieVCCVmywBowT";

$timestamp = date("YmdHis");
$password = base64_encode($shortcode.$passkey.$timestamp);

/* GET ACCESS TOKEN */

$credentials = base64_encode($consumerKey.":".$consumerSecret);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,"https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials");
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Authorization: Basic ".$credentials]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$tokenRaw = curl_exec($curl);
$tokenError = curl_error($curl);
$response = json_decode($tokenRaw ?: '', true);
curl_close($curl);

if ($tokenError || empty($response['access_token'])) {
    http_response_code(502);
    echo json_encode(["status" => "error", "message" => "M-Pesa authentication failed. Please try again shortly."]);
    exit();
}

$access_token = $response['access_token'];


/* STK PUSH */

$url = "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest";

$payload = [
"BusinessShortCode"=>$shortcode,
"Password"=>$password,
"Timestamp"=>$timestamp,
"TransactionType"=>"CustomerPayBillOnline",
"Amount"=>$kes,
"PartyA"=>$phone,
"PartyB"=>$shortcode,
"PhoneNumber"=>$phone,
"CallBackURL"=>"https://yourdomain.com/callback_url.php",
"AccountReference"=>"TradingDeposit",
"TransactionDesc"=>"Deposit"
];

$curl = curl_init($url);

curl_setopt($curl,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$access_token,
"Content-Type: application/json"
]);

curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($payload));

$stkRaw = curl_exec($curl);
$stkError = curl_error($curl);
$result = json_decode($stkRaw ?: '', true);
curl_close($curl);

$checkout_id = $result['CheckoutRequestID'] ?? null;

// Do not create a pending deposit unless Safaricom accepted the STK push.
if ($stkError || !$checkout_id || ($result['ResponseCode'] ?? '') !== '0') {
    http_response_code(502);
    echo json_encode([
        "status" => "error",
        "message" => $result['errorMessage'] ?? $result['ResponseDescription'] ?? "M-Pesa did not accept the STK request."
    ]);
    exit();
}


/* SAVE PENDING DEPOSIT */

$stmt = $conn->prepare("INSERT INTO deposits (user_id,amount_usd,amount_kes,phone,checkout_request_id) VALUES (?,?,?,?,?)");

$stmt->bind_param("iddss",$user_id,$usd,$kes,$phone,$checkout_id);
if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Could not save the payment request."]);
    exit();
}

echo json_encode([
"status"=>"stk_sent",
"checkout"=>$checkout_id
]);
