<?php

require_once '../../core/api_bootstrap.php';
require_once '../../core/provider_auth.php';

$provider_id = ProviderAuth::id();
$data = Request::post();

try {

    Validator::required($data, ['plan_id']);

    $db = new Database();
    $conn = $db->connect();

    /* GET PLAN */

    $stmt = $conn->prepare("
SELECT id,name,price
FROM plans
WHERE id=:id
AND status=1
LIMIT 1
");

    $stmt->execute([
        ':id' => $data['plan_id']
    ]);

    $plan = $stmt->fetch();

    if (!$plan) {
        Response::error("Invalid plan");
    }

    /* CREATE RAZORPAY ORDER */

    $orderData = [
        "amount" => $plan['price'] * 100,
        "currency" => "INR",
        "receipt" => "plan_" . $plan['id'] . "_" . time(),
        "notes" => [
            "provider_id" => $provider_id,
            "plan_id" => $plan['id']
        ]
    ];

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => "https://api.razorpay.com/v1/orders",
        CURLOPT_USERPWD => RAZORPAY_KEY . ":" . RAZORPAY_SECRET,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($orderData),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json"
        ]
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if (!isset($result['id'])) {
        Response::error("Unable to create order");
    }

    /* STORE PAYMENT */

    $stmt = $conn->prepare("
INSERT INTO payments
(provider_id,plan_id,razorpay_order_id,amount,status)
VALUES
(:provider,:plan,:order,:amount,'created')
");

    $stmt->execute([
        ':provider' => $provider_id,
        ':plan' => $plan['id'],
        ':order' => $result['id'],
        ':amount' => $plan['price']
    ]);

    Response::success([
        'order_id' => $result['id'],
        'amount' => $plan['price'],
        'key' => RAZORPAY_KEY
    ]);

} catch (Exception $e) {

    Logger::log("payments.log", $e->getMessage());
    Response::error("Payment error", 500);

}