<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    jsonResponse(['status' => 'unauthorized', 'message' => 'Not logged in'], 401);
}

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    jsonResponse(['status' => 'unauthorized', 'message' => 'Invalid user'], 401);
}

csrfVerify();
$action = $_POST['action'] ?? '';

if ($action === 'create') {
    $amount = floatval($_POST['amount'] ?? 0);
    $slug = trim($_POST['slug'] ?? '');
    $expiry = trim($_POST['expiry'] ?? '24h');

    if ($amount <= 0) {
        jsonResponse(['status' => 'error', 'message' => 'Invalid amount.']);
    }
    
    if (!empty($slug) && !preg_match('/^[a-zA-Z0-9_-]+$/', $slug)) {
        jsonResponse(['status' => 'error', 'message' => 'Slug can only contain letters, numbers, dashes and underscores.']);
    }

    $expiresAt = time() + 86400;
    if (preg_match('/^(\d+)(m|h)$/', $expiry, $matches)) {
        $val = intval($matches[1]);
        $unit = $matches[2];
        if ($unit === 'm') {
            $expiresAt = time() + ($val * 60);
        } elseif ($unit === 'h') {
            $expiresAt = time() + ($val * 3600);
        }
    }

    $result = createPaymentLink($user['id'], $amount, $slug, $expiresAt);
    if (!$result['success']) {
        jsonResponse(['status' => 'error', 'message' => $result['error']]);
    }
    jsonResponse(['status' => 'success', 'slug' => $result['slug']]);

} elseif ($action === 'expire') {
    $slug = $_POST['slug'] ?? '';
    $link = getPaymentLinkBySlug($slug);
    
    if (!$link || $link['user_id'] !== $user['id']) {
        jsonResponse(['status' => 'error', 'message' => 'Link not found.']);
    }
    
    updatePaymentLink($slug, 'expired');
    jsonResponse(['status' => 'success']);

} elseif ($action === 'unexpire' || $action === 'reactivate') {
    $slug = $_POST['slug'] ?? '';
    $expiry = trim($_POST['expiry'] ?? '');
    $expiresAt = null;
    
    if (!empty($expiry) && preg_match('/^(\d+)(m|h)$/', $expiry, $matches)) {
        $val = intval($matches[1]);
        $unit = $matches[2];
        if ($unit === 'm') {
            $expiresAt = time() + ($val * 60);
        } elseif ($unit === 'h') {
            $expiresAt = time() + ($val * 3600);
        }
    }
    
    $result = reactivatePaymentLink($slug, $user['id'], $expiresAt);
    if (!$result['success']) {
        jsonResponse(['status' => 'error', 'message' => $result['error']]);
    }
    jsonResponse(['status' => 'success']);

} elseif ($action === 'disable') {
    $slug = $_POST['slug'] ?? '';
    $link = getPaymentLinkBySlug($slug);
    
    if (!$link || $link['user_id'] !== $user['id']) {
        jsonResponse(['status' => 'error', 'message' => 'Link not found.']);
    }
    
    updatePaymentLink($slug, 'disabled');
    jsonResponse(['status' => 'success']);
}

jsonResponse(['status' => 'error', 'message' => 'Invalid action.']);
