<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    date_default_timezone_set("Africa/Lagos");

    $user_id = mysqli_real_escape_string($con, $_POST['user_id'] ?? '');
    $auth    = mysqli_real_escape_string($con, $_POST['auth'] ?? '');

    $response = [];

    if (empty($user_id) || empty($auth)) {
        $response['success'] = false;
        $response['message'] = 'Missing required fields: user_id or auth';
        echo json_encode($response);
        exit();
    }

    // ✅ Check if user exists
    $user_query = $con->prepare("SELECT id FROM users WHERE user_id = ? AND auth = ? LIMIT 1");
    if (!$user_query) {
        $response['success'] = false;
        $response['message'] = 'Database error: ' . $con->error;
        echo json_encode($response);
        exit();
    }

    $user_query->bind_param("ss", $user_id, $auth);
    $user_query->execute();
    $result = $user_query->get_result();

    if ($result->num_rows > 0) {
        // ✅ Fetch subscription history
        $sub_query = $con->prepare("
            SELECT id, package, amount, narration, stripe_session_id, status, created_at
            FROM pending_package_subscriptions
            WHERE user_id = ? AND status = 'completed'
            ORDER BY created_at DESC
        ");
        if (!$sub_query) {
            $response['success'] = false;
            $response['message'] = 'Database error: ' . $con->error;
            echo json_encode($response);
            exit();
        }

        $sub_query->bind_param("s", $user_id);
        $sub_query->execute();
        $sub_result = $sub_query->get_result();

        $history = [];
        while ($row = $sub_result->fetch_assoc()) {
            $history[] = $row;
        }

        $response['success'] = true;
        $response['status']  = 'success';
        $response['data']    = $history;

        $sub_query->close();
    } else {
        $response['success'] = false;
        $response['message'] = 'Invalid authentication';
    }

    $user_query->close();
} else {
    $response['success'] = false;
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);
$con->close();
