<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']);
    exit();
}

require_once '../include/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$purchase_id   = filter_var($_POST['purchase_id']   ?? 0, FILTER_VALIDATE_INT);
$refund_reason = trim($_POST['refund_reason']        ?? '');
$user_id       = (int)$_SESSION['user_id'];

if (!$purchase_id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid purchase ID']);
    exit();
}

if (strlen($refund_reason) < 10) {
    echo json_encode(['status' => '0', 'msg' => 'Please provide a more detailed reason (at least 10 characters)']);
    exit();
}

try {
    // Fetch the purchase
    $stmt = $pdo->prepare("SELECT * FROM sm_purchases WHERE id = :id AND user_id = :uid LIMIT 1");
    $stmt->execute(['id' => $purchase_id, 'uid' => $user_id]);
    $purchase = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$purchase) {
        echo json_encode(['status' => '0', 'msg' => 'Purchase not found']);
        exit();
    }

    if ($purchase['status'] !== 'completed') {
        echo json_encode(['status' => '0', 'msg' => 'This purchase is not eligible for a refund request']);
        exit();
    }

    // Check 30-minute window
    $mins_since = (time() - strtotime($purchase['purchase_date'])) / 60;
    if ($mins_since > 30) {
        echo json_encode(['status' => '0', 'msg' => 'Refund window has expired. Refunds are only available within 30 minutes of purchase.']);
        exit();
    }

    // Update status to refund_pending
    $pdo->prepare("UPDATE sm_purchases SET status = 'refund_pending', refund_reason = :reason WHERE id = :id AND user_id = :uid")
        ->execute(['reason' => $refund_reason, 'id' => $purchase_id, 'uid' => $user_id]);

    echo json_encode([
        'status' => '1',
        'msg'    => 'Refund request submitted successfully. An admin will review it shortly.'
    ]);

} catch (PDOException $e) {
    error_log('request_log_refund.php error: ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'A server error occurred. Please try again.']);
}
?>