<?php
require 'db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// ?? GET USER DATA
$res = mysqli_query($conn, "
    SELECT id, verified, payment_status 
    FROM users 
    WHERE id='$user_id' 
    LIMIT 1
");

$user = mysqli_fetch_assoc($res);

// ? INVALID USER
if (!$user) {
    session_destroy();
    header("Location: ../login.php");
    exit;
}

// ?? NOT VERIFIED ? VERIFY FIRST
if ($user['verified'] == 0) {
    header("Location: ../verify_details.php");
    exit;
}

// ?? STEP 3: BILLING LOCK
$billingCheck = mysqli_query($conn, "
    SELECT id FROM billings 
    WHERE user_id='$user_id' AND status='pending'
    LIMIT 1
");

if (mysqli_num_rows($billingCheck) > 0) {
    header("Location: ../billing.php");
    exit;
}


// ?? STEP 4: PAYMENT LOCK
if ($user['payment_status'] == 0) {

    if (empty($user['payment_expires_at'])) {

        $expiry = date("Y-m-d H:i:s", time() + 86400);

        mysqli_query($conn, "
            UPDATE users 
            SET payment_expires_at='$expiry'
            WHERE id='$user_id'
        ");
    }

    header("Location: ../account_secured.php");
    exit;
}

// ? VERIFIED + PAID ? DASHBOARD
header("Location: ../dashboard.php");
exit;