
<?php
// /htdocs/pages/api/loyalty.php — Loyalty JSON API
// Existing actions preserved.
// Vendor actions:
//   vendor_loyalty_status, vendor_loyalty_toggle,
//   vendor_redeem, vendor_redemptions
//
// Router slug: api-loyalty

if (!defined('APP_START')) {
    http_response_code(403);
    exit(json_encode(['success' => false, 'message' => 'Direct access denied']));
}

require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../database.php';
require_once __DIR__ . '/../../functions.php';

if (!function_exists('loyalty') && is_file(__DIR__ . '/../../includes/loyalty.php')) {
    require_once __DIR__ . '/../../includes/loyalty.php';
}
if (!function_exists('gamification') && is_file(__DIR__ . '/../../includes/gamification.php')) {
    require_once __DIR__ . '/../../includes/gamification.php';
}

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate');

function loyaltyApiResponse(array $data, int $status = 200): void
{
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

function loyaltyApiRequirePost(): void
{
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        loyaltyApiResponse([
            'success' => false,
            'message' => 'POST required'
        ], 405);
    }
}

/**
 * A vendor must be explicitly selected and owned by the logged-in user.
 * Never select a vendor using user_id alone because users may own
 * multiple vendor records.
 */
function loyaltyApiOwnedVendor(int $vendorId, int $userId): ?array
{
    if ($vendorId <= 0 || $userId <= 0) {
        return null;
    }

    return db()->fetchOne(
        "SELECT id, user_id, company_name, is_approved, is_active,
                status, accepts_loyalty, loyalty_accepted_at, currency
         FROM vendors
         WHERE id = ? AND user_id = ?
         LIMIT 1",
        [$vendorId, $userId]
    ) ?: null;
}

// ============================================
// AUTH
// ============================================
if (!isLoggedIn()) {
    loyaltyApiResponse([
        'success' => false,
        'requires_login' => true,
        'message' => 'Please log in'
    ], 401);
}

$userId = (int)($_SESSION['user_id'] ?? 0);

if ($userId <= 0) {
    loyaltyApiResponse([
        'success' => false,
        'message' => 'Invalid session'
    ], 401);
}

// ============================================
// PARSE INPUT
// ============================================
$rawBody = file_get_contents('php://input');
$jsonBody = null;

if ($rawBody !== false && $rawBody !== '') {
    $decoded = json_decode($rawBody, true);
    if (is_array($decoded)) {
        $jsonBody = $decoded;
    }
}

if ($jsonBody === null && !empty($_POST)) {
    $jsonBody = $_POST;
}

if ($jsonBody === null) {
    $jsonBody = [];
}

$action = '';

if (!empty($_GET['action'])) {
    $action = (string)$_GET['action'];
} elseif (!empty($jsonBody['action'])) {
    $action = (string)$jsonBody['action'];
}

$loy = function_exists('loyalty') ? loyalty() : null;
$gam = function_exists('gamification') ? gamification() : null;

// ============================================
// DISPATCH
// ============================================
try {
    switch ($action) {

        // ====================================
        // MEMBER CATALOGUE REDEMPTION
        // ====================================
        case 'redeem':
            loyaltyApiRequirePost();

            if (!$loy || !method_exists($loy, 'redeem')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Redemption unavailable'
                ], 500);
            }

            $rewardId = (int)($jsonBody['reward_id'] ?? 0);

            if ($rewardId <= 0) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Invalid reward'
                ], 400);
            }

            $result = $loy->redeem($userId, $rewardId);

            if (!is_array($result)) {
                $result = [
                    'success' => false,
                    'message' => 'Unexpected redemption response'
                ];
            }

            if (!isset($result['success'])) {
                $result['success'] = false;
            }

            loyaltyApiResponse($result);
            break;

        // ====================================
        // MEMBER BALANCE
        // ====================================
        case 'balance':
            if (!$loy || !method_exists($loy, 'getBalance')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Balance unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'balance' => $loy->getBalance($userId)
            ]);
            break;

        // ====================================
        // REWARDS CATALOGUE
        // ====================================
        case 'rewards':
            if (!$loy || !method_exists($loy, 'getRewards')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Rewards unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'rewards' => $loy->getRewards($userId)
            ]);
            break;

        // ====================================
        // MEMBER POINT HISTORY
        // ====================================
        case 'history':
            if (!$loy || !method_exists($loy, 'getHistory')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'History unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'history' => $loy->getHistory($userId, 50)
            ]);
            break;

        // ====================================
        // MEMBER CATALOGUE REDEMPTIONS
        // ====================================
        case 'redemptions':
            if (!$loy || !method_exists($loy, 'getRedemptions')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Redemptions unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'redemptions' => $loy->getRedemptions($userId, 50)
            ]);
            break;

        // ====================================
        // VENDOR: ACCEPTANCE STATUS
        // ====================================
        case 'vendor_loyalty_status':
            $vendorId = (int)($_GET['vendor_id'] ?? $jsonBody['vendor_id'] ?? 0);
            $vendor = loyaltyApiOwnedVendor($vendorId, $userId);

            if (!$vendor) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor not found or access denied'
                ], 403);
            }

            loyaltyApiResponse([
                'success' => true,
                'vendor' => [
                    'id' => (int)$vendor['id'],
                    'company_name' => $vendor['company_name'],
                    'accepts_loyalty' => (int)$vendor['accepts_loyalty'],
                    'loyalty_accepted_at' => $vendor['loyalty_accepted_at'],
                    'eligible' =>
                        (int)$vendor['is_approved'] === 1
                        && (int)$vendor['is_active'] === 1
                        && strtolower((string)$vendor['status']) === 'active'
                ]
            ]);
            break;

        // ====================================
        // VENDOR: ENABLE / DISABLE ACCEPTANCE
        // ====================================
        case 'vendor_loyalty_toggle':
            loyaltyApiRequirePost();

            $vendorId = (int)($jsonBody['vendor_id'] ?? 0);
            $enabled = isset($jsonBody['enabled'])
                ? (int)(bool)$jsonBody['enabled']
                : -1;

            if ($vendorId <= 0 || !in_array($enabled, [0, 1], true)) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Invalid vendor or acceptance setting'
                ], 400);
            }

            $vendor = loyaltyApiOwnedVendor($vendorId, $userId);

            if (!$vendor) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor not found or access denied'
                ], 403);
            }

            if ($enabled === 1) {
                $eligible =
                    (int)$vendor['is_approved'] === 1
                    && (int)$vendor['is_active'] === 1
                    && strtolower((string)$vendor['status']) === 'active';

                if (!$eligible) {
                    loyaltyApiResponse([
                        'success' => false,
                        'message' => 'This vendor must be approved and active before accepting loyalty points'
                    ], 403);
                }

                db()->query(
                    "UPDATE vendors
                     SET accepts_loyalty = 1,
                         loyalty_accepted_at = NOW()
                     WHERE id = ? AND user_id = ?",
                    [$vendorId, $userId]
                );
            } else {
                db()->query(
                    "UPDATE vendors
                     SET accepts_loyalty = 0,
                         loyalty_accepted_at = NULL
                     WHERE id = ? AND user_id = ?",
                    [$vendorId, $userId]
                );
            }

            loyaltyApiResponse([
                'success' => true,
                'vendor_id' => $vendorId,
                'accepts_loyalty' => $enabled,
                'message' => $enabled
                    ? 'Your vendor is now accepting Revenda loyalty points'
                    : 'Loyalty acceptance has been disabled'
            ]);
            break;

        // ====================================
        // VENDOR: REDEEM MEMBER POINTS
        // ====================================
        case 'vendor_redeem':
            loyaltyApiRequirePost();

            if (!$loy || !method_exists($loy, 'redeemAtVendor')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor redemption service unavailable'
                ], 500);
            }

            $vendorId = (int)($jsonBody['vendor_id'] ?? 0);
            $memberId = (int)($jsonBody['member_id'] ?? 0);
            $points = (int)($jsonBody['points'] ?? 0);

            $settlementChoice = strtolower(trim(
                (string)($jsonBody['settlement_choice'] ?? '')
            ));

            $idempotencyKey = trim(
                (string)($jsonBody['idempotency_key'] ?? '')
            );

            $cashPercent = (float)($jsonBody['cash_percent'] ?? 50);
            $description = trim((string)($jsonBody['description'] ?? ''));
            $reference = trim((string)($jsonBody['reference'] ?? ''));

            if ($vendorId <= 0 || $memberId <= 0 || $points <= 0) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor, member and valid points amount are required'
                ], 400);
            }

            if (!in_array($settlementChoice, ['cash', 'credit', 'split'], true)) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Settlement choice must be cash, credit or split'
                ], 400);
            }

            if (
                $idempotencyKey === ''
                || strlen($idempotencyKey) < 16
                || strlen($idempotencyKey) > 100
            ) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'A valid idempotency key is required'
                ], 400);
            }

            if ($settlementChoice === 'split' && ($cashPercent <= 0 || $cashPercent >= 100)) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Split cash percentage must be between 1 and 99'
                ], 400);
            }

            // Explicit vendor ownership check.
            // The logged-in user is the vendor operator.
            $vendor = loyaltyApiOwnedVendor($vendorId, $userId);

            if (!$vendor) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor not found or access denied'
                ], 403);
            }

            if (
                (int)$vendor['is_approved'] !== 1
                || (int)$vendor['is_active'] !== 1
                || strtolower((string)$vendor['status']) !== 'active'
            ) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'This vendor is not currently eligible for loyalty redemption'
                ], 403);
            }

            if ((int)$vendor['accepts_loyalty'] !== 1) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'This vendor is not accepting loyalty points'
                ], 403);
            }

            // The engine performs the transaction, member balance lock,
            // idempotency check, ledger deduction and settlement creation.
            $result = $loy->redeemAtVendor(
                $memberId,
                $vendorId,
                $points,
                $settlementChoice,
                $idempotencyKey,
                $cashPercent,
                $description,
                $reference,
                $userId
            );

            if (!is_array($result)) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Unexpected vendor redemption response'
                ], 500);
            }

            if (!isset($result['success'])) {
                $result['success'] = false;
            }

            loyaltyApiResponse($result);
            break;

        // ====================================
        // VENDOR: REDEMPTION HISTORY
        // ====================================
        case 'vendor_redemptions':
            $vendorId = (int)($_GET['vendor_id'] ?? $jsonBody['vendor_id'] ?? 0);
            $vendor = loyaltyApiOwnedVendor($vendorId, $userId);

            if (!$vendor) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Vendor not found or access denied'
                ], 403);
            }

            $limit = (int)($_GET['limit'] ?? $jsonBody['limit'] ?? 50);
            $limit = max(1, min(100, $limit));

            $rows = db()->fetchAll(
                "SELECT id, redemption_code, user_id, points_spent,
                        cash_rate, credit_rate, cash_value, credit_value,
                        currency, status, description, reference,
                        created_at, confirmed_at, reversed_at
                 FROM vendor_loyalty_redemptions
                 WHERE vendor_id = ?
                 ORDER BY id DESC
                 LIMIT {$limit}",
                [$vendorId]
            );

            loyaltyApiResponse([
                'success' => true,
                'vendor_id' => $vendorId,
                'redemptions' => is_array($rows) ? $rows : []
            ]);
            break;

        // ====================================
        // ACHIEVEMENTS
        // ====================================
        case 'achievements':
            if (!$gam || !method_exists($gam, 'getUserAchievements')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Achievements unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'achievements' => $gam->getUserAchievements($userId)
            ]);
            break;

        // ====================================
        // CHALLENGES
        // ====================================
        case 'challenges':
            if (!$gam || !method_exists($gam, 'getChallenges')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Challenges unavailable'
                ], 500);
            }

            loyaltyApiResponse([
                'success' => true,
                'challenges' => $gam->getChallenges($userId)
            ]);
            break;

        // ====================================
        // JOIN CHALLENGE
        // ====================================
        case 'join_challenge':
            loyaltyApiRequirePost();

            if (!$gam || !method_exists($gam, 'joinChallenge')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Join unavailable'
                ], 500);
            }

            $challengeId = (int)($jsonBody['challenge_id'] ?? 0);

            if ($challengeId <= 0) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Invalid challenge'
                ], 400);
            }

            $ok = $gam->joinChallenge($userId, $challengeId);

            loyaltyApiResponse([
                'success' => (bool)$ok
            ]);
            break;

        // ====================================
        // LEADERBOARD
        // ====================================
        case 'leaderboard':
            if (!$gam || !method_exists($gam, 'getLeaderboard')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Leaderboard unavailable'
                ], 500);
            }

            $period = (string)($_GET['period'] ?? $jsonBody['period'] ?? 'weekly');
            $limit = (int)($_GET['limit'] ?? $jsonBody['limit'] ?? 50);
            $limit = max(1, min(100, $limit));

            loyaltyApiResponse([
                'success' => true,
                'leaderboard' => $gam->getLeaderboard($period, $limit),
                'period' => $period
            ]);
            break;

        // ====================================
        // MEMBER RANK
        // ====================================
        case 'rank':
            if (!$gam || !method_exists($gam, 'getUserRank')) {
                loyaltyApiResponse([
                    'success' => false,
                    'message' => 'Rank unavailable'
                ], 500);
            }

            $period = (string)($_GET['period'] ?? $jsonBody['period'] ?? 'weekly');

            loyaltyApiResponse([
                'success' => true,
                'rank' => $gam->getUserRank($userId, $period),
                'period' => $period
            ]);
            break;

        // ====================================
        // STREAK
        // ====================================
        case 'streak':
            $streak = [
                'current_streak' => 0,
                'longest_streak' => 0,
                'last_activity_date' => null
            ];

            try {
                $row = db()->fetchOne(
                    "SELECT * FROM user_streaks WHERE user_id = ?",
                    [$userId]
                );

                if (is_array($row)) {
                    $streak['current_streak'] = (int)($row['current_streak'] ?? 0);
                    $streak['longest_streak'] = (int)($row['longest_streak'] ?? 0);
                    $streak['last_activity_date'] = $row['last_activity_date'] ?? null;
                }
            } catch (Throwable $e) {
                error_log('Loyalty API streak: ' . $e->getMessage());
            }

            loyaltyApiResponse([
                'success' => true,
                'streak' => $streak
            ]);
            break;

        // ====================================
        // SUMMARY
        // ====================================
        case 'summary':
            $summary = [
                'balance' => null,
                'streak' => null,
                'achievements' => null,
                'challenges' => null,
                'rank' => null
            ];

            if ($loy && method_exists($loy, 'getBalance')) {
                try {
                    $summary['balance'] = $loy->getBalance($userId);
                } catch (Throwable $e) {
                    error_log('Loyalty API summary balance: ' . $e->getMessage());
                }
            }

            try {
                $row = db()->fetchOne(
                    "SELECT * FROM user_streaks WHERE user_id = ?",
                    [$userId]
                );

                if (is_array($row)) {
                    $summary['streak'] = $row;
                }
            } catch (Throwable $e) {}

            if ($gam && method_exists($gam, 'getUserAchievements')) {
                try {
                    $summary['achievements'] = $gam->getUserAchievements($userId);
                } catch (Throwable $e) {}
            }

            if ($gam && method_exists($gam, 'getChallenges')) {
                try {
                    $summary['challenges'] = $gam->getChallenges($userId);
                } catch (Throwable $e) {}
            }

            if ($gam && method_exists($gam, 'getUserRank')) {
                try {
                    $summary['rank'] = $gam->getUserRank($userId, 'weekly');
                } catch (Throwable $e) {}
            }

            loyaltyApiResponse([
                'success' => true,
                'summary' => $summary
            ]);
            break;

        // ====================================
        // UNKNOWN ACTION
        // ====================================
        default:
            loyaltyApiResponse([
                'success' => false,
                'message' => 'Unknown or missing action',
                'action_received' => $action,
                'valid_actions' => [
                    'redeem',
                    'balance',
                    'rewards',
                    'history',
                    'redemptions',
                    'vendor_loyalty_status',
                    'vendor_loyalty_toggle',
                    'vendor_redeem',
                    'vendor_redemptions',
                    'achievements',
                    'challenges',
                    'join_challenge',
                    'leaderboard',
                    'rank',
                    'streak',
                    'summary'
                ]
            ], 400);
    }

} catch (Throwable $e) {
    error_log(
        'api/loyalty error: '
        . $e->getMessage()
        . ' @ '
        . $e->getFile()
        . ':'
        . $e->getLine()
    );

    loyaltyApiResponse([
        'success' => false,
        'message' => 'Server error while processing request'
    ], 500);
}