<?php

class UnblockController {

    // ─── GET /api/user/unblock-details ──────────────────────────────────────────
    public static function getUnblockDetails(): void {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit();
        }

        // We manually verify the token here because requireAuth() blocks 403 users.
        $token = getBearerToken();
        if (!$token) sendError('Unauthorized: No token provided', 401);
        
        $data = AuthController::verifyToken($token);
        if (!$data) sendError('Unauthorized: Invalid or expired token', 401);
        
        $userId = (int)$data['id'];
        $db = getDb();
        
        // Calculate total security deposit for overdue/return-requested items
        $stmt = $db->prepare("
            SELECT SUM(oi.security_deposit * oi.quantity) as total_deposit
            FROM orders o
            JOIN order_items oi ON oi.order_id = o.id
            WHERE o.user_id = ? 
            AND (o.status IN ('Overdue', 'Return Requested') OR o.refund_status = 'blocked_penalty')
        ");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $totalDeposit = (float)($res['total_deposit'] ?? 0);
        $stmt->close();

        if ($totalDeposit <= 0) {
            sendError('No outstanding deposits found to settle.', 400);
        }

        $unblockAmount = round($totalDeposit * 1.2, 2); // Deposit + 20%

        sendSuccess([
            'total_deposit'  => $totalDeposit,
            'unblock_amount' => $unblockAmount,
            'currency'      => 'INR'
        ]);
    }

    // ─── POST /api/user/initiate-unblock ─────────────────────────────────────────
    public static function initiateUnblock(): void {
        $token = getBearerToken();
        if (!$token) sendError('Unauthorized', 401);
        $data = AuthController::verifyToken($token);
        if (!$data) sendError('Unauthorized', 401);
        $userId = (int)$data['id'];

        $db = getDb();
        
        $stmt = $db->prepare("
            SELECT SUM(oi.security_deposit * oi.quantity) as total_deposit
            FROM orders o
            JOIN order_items oi ON oi.order_id = o.id
            WHERE o.user_id = ? 
            AND (o.status IN ('Overdue', 'Return Requested') OR o.refund_status = 'blocked_penalty')
        ");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $totalDeposit = (float)($res['total_deposit'] ?? 0);
        $stmt->close();

        if ($totalDeposit <= 0) sendError('Nothing to pay', 400);

        $unblockAmount = round($totalDeposit * 1.2, 2);
        $amountInPaise = (int) round($unblockAmount * 100);

        $ch = curl_init('https://api.razorpay.com/v1/orders');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_USERPWD => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode([
                'amount'   => $amountInPaise,
                'currency' => 'INR',
                'receipt'  => "unblock_payment_$userId"
            ])
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            sendError('Razorpay order creation failed: ' . ($response ?: 'Unknown error'), 500);
        }

        sendSuccess(['razorpay_order' => json_decode($response, true)]);
    }

    // ─── POST /api/user/verify-unblock ───────────────────────────────────────────
    public static function verifyUnblock(): void {
        $token = getBearerToken();
        if (!$token) sendError('Unauthorized', 401);
        $data = AuthController::verifyToken($token);
        if (!$data) sendError('Unauthorized', 401);
        $userId = (int)$data['id'];

        $body = getJsonBody();
        $paymentId = trim($body['razorpay_payment_id'] ?? '');
        $orderId   = trim($body['razorpay_order_id'] ?? '');
        $signature = trim($body['razorpay_signature'] ?? '');

        if (!$paymentId || !$orderId || !$signature) {
            sendError('Invalid request: Missing payment data', 422);
        }

        // Verify signature
        $generated = hash_hmac('sha256', "$orderId|$paymentId", RAZORPAY_KEY_SECRET);
        if (!hash_equals($generated, $signature)) {
            sendError('Invalid signature: Security failure', 400);
        }

        $db = getDb();
        
        // 1. Unblock the User & Apply manual override
        $db->query("UPDATE users SET status = 'active', manual_unblock = 1 WHERE id = $userId");

        // 2. Clear all overdue orders for this user (assume settled)
        $db->query("
            UPDATE orders 
            SET status = 'Returned', 
                payment_status = 'Settled',
                special_instructions = CONCAT(IFNULL(special_instructions, ''), '\n[System]: Account unblocked via settlement payment.')
            WHERE user_id = $userId 
            AND (status IN ('Overdue', 'Return Requested') OR refund_status = 'blocked_penalty')
        ");

        sendSuccess(null, 'Account successfully unblocked! You can now access your dashboard.');
    }
}
