<?php
// razorpay/verify_payment.php — Verify Razorpay payment after checkout
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../helpers.php';

header('Content-Type: application/json');

$store = requireAuth();
$input = json_decode(file_get_contents('php://input'), true);

$paymentId      = $input['razorpay_payment_id'] ?? '';
$subscriptionId = $input['razorpay_subscription_id'] ?? '';
$signature      = $input['razorpay_signature'] ?? '';

if (empty($paymentId) || empty($subscriptionId) || empty($signature)) {
    jsonResponse(['success' => false, 'message' => 'Missing payment details'], 400);
}

// Verify signature
$generatedSig = hash_hmac('sha256', $paymentId . '|' . $subscriptionId, RAZORPAY_KEY_SECRET);
$isValid = hash_equals($generatedSig, $signature);

if (!$isValid) {
    jsonResponse(['success' => false, 'message' => 'Payment verification failed. Invalid signature.'], 400);
}

$db = getDB();

// Update subscription to active
$stmt = $db->prepare("
    UPDATE subscriptions SET
        status = 'active',
        razorpay_payment_id = ?,
        current_start = NOW(),
        current_end   = DATE_ADD(NOW(), INTERVAL 1 MONTH),
        updated_at    = NOW()
    WHERE razorpay_subscription_id = ? AND store_id = ?
");
$stmt->execute([$paymentId, $subscriptionId, $store['id']]);

// Get subscription details for payment log
$subStmt = $db->prepare("SELECT id, plan_id FROM subscriptions WHERE razorpay_subscription_id = ? AND store_id = ?");
$subStmt->execute([$subscriptionId, $store['id']]);
$subData = $subStmt->fetch();

if ($subData) {
    // Get plan price
    $planStmt = $db->prepare("SELECT price FROM plans WHERE id = ?");
    $planStmt->execute([$subData['plan_id']]);
    $planPrice = $planStmt->fetchColumn();

    // Log payment
    $payStmt = $db->prepare("
        INSERT INTO payments (store_id, subscription_id, razorpay_payment_id, amount, currency, status, paid_at)
        VALUES (?, ?, ?, ?, 'INR', 'captured', NOW())
    ");
    $payStmt->execute([
        $store['id'],
        $subData['id'],
        $paymentId,
        $planPrice,
    ]);
}

jsonResponse([
    'success' => true,
    'message' => 'Subscription activated successfully!',
]);
