<?php

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

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

try {

    Validator::required($data, [
        'razorpay_order_id',
        'razorpay_payment_id',
        'razorpay_signature'
    ]);

    $order_id = $data['razorpay_order_id'];
    $payment_id = $data['razorpay_payment_id'];
    $signature = $data['razorpay_signature'];

    /* VERIFY SIGNATURE */

    $generated = hash_hmac(
        'sha256',
        $order_id . "|" . $payment_id,
        RAZORPAY_SECRET
    );

    if ($generated !== $signature) {
        Response::error("Payment verification failed");
    }

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

    /* GET PAYMENT */

    $stmt = $conn->prepare("
SELECT *
FROM payments
WHERE razorpay_order_id=:order
LIMIT 1
");

    $stmt->execute([
        ':order' => $order_id
    ]);

    $payment = $stmt->fetch();

    if (!$payment) {
        Response::error("Payment record not found");
    }

    /* UPDATE PAYMENT */

    $conn->prepare("
UPDATE payments
SET
razorpay_payment_id=:payment,
razorpay_signature=:signature,
status='paid'
WHERE razorpay_order_id=:order
")->execute([
                ':payment' => $payment_id,
                ':signature' => $signature,
                ':order' => $order_id
            ]);

    /* GET PLAN */

    $stmt = $conn->prepare("
SELECT *
FROM plans
WHERE id=:plan
");

    $stmt->execute([
        ':plan' => $payment['plan_id']
    ]);

    $plan = $stmt->fetch();

    /* EXPIRE OLD SUBSCRIPTION */

    $conn->prepare("
UPDATE provider_subscriptions
SET status='expired'
WHERE provider_id=:provider
AND status='active'
")->execute([
                ':provider' => $provider_id
            ]);

    /* ACTIVATE NEW SUBSCRIPTION */

    $conn->prepare("
INSERT INTO provider_subscriptions
(provider_id,plan_id,plan_name,plan_price,categories_allowed,daily_lead_limit,validity_days,start_date,expiry_date,status)

VALUES
(:provider,:plan,:name,:price,:cat,:lead,:days,CURDATE(),DATE_ADD(CURDATE(),INTERVAL :days DAY),'active')

")->execute([

                ':provider' => $provider_id,
                ':plan' => $plan['id'],
                ':name' => $plan['name'],
                ':price' => $plan['price'],
                ':cat' => $plan['categories_allowed'],
                ':lead' => $plan['daily_lead_limit'],
                ':days' => $plan['validity_days']

            ]);

    Response::success([], "Subscription activated");

} catch (Exception $e) {

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

}