<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Services\ApkService;

class HomeController extends Controller {
    
    public function index() {
        $category = $_GET['category'] ?? null;
        $search = $_GET['search'] ?? null;
        
        // Store referral code if present in landing
        if (isset($_GET['ref'])) {
            $_SESSION['global_ref'] = $_GET['ref'];
        }

        $apkService = new ApkService();
        $apks = $apkService->getAllApks($category, $search);
        
        // Handle AJAX requests for filtering/searching
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            $this->view('partials/apk_list', [
                'apks' => $apks
            ]);
            return;
        }

        $this->view('home', [
            'apks' => $apks,
            'title' => get_setting('site_name', 'ApkNusa') . __('home_title_suffix')
        ]);
    }

    public function apkDetail($params) {
        $slug = $params['slug'];
        $db = db_pdo();
        $stmt = $db->prepare("SELECT * FROM apks WHERE slug = ?");
        $stmt->execute([$slug]);
        $apk = $stmt->fetch();

        if (!$apk) {
            if (ob_get_level() > 0) ob_clean();
            header("HTTP/1.0 404 Not Found");
            $this->view('404');
            return;
        }

        // Store referral code if present specifically for this APK or take from global session
        if (isset($_GET['ref'])) {
            $_SESSION['ref_download_' . $apk['id']] = $_GET['ref'];
        } elseif (isset($_SESSION['global_ref'])) {
            $_SESSION['ref_download_' . $apk['id']] = $_SESSION['global_ref'];
        }

        $this->view('apk_detail', [
            'apk' => $apk,
            'title' => $apk['title'] . ' - ' . get_setting('site_name', 'ApkNusa')
        ]);
    }

    public function download($params) {
        $slug = $params['slug'];
        $db = db_pdo();
        $stmt = $db->prepare("SELECT * FROM apks WHERE slug = ?");
        $stmt->execute([$slug]);
        $apk = $stmt->fetch();

        if (!$apk) {
            if (ob_get_level() > 0) ob_clean();
            header("HTTP/1.0 404 Not Found");
            $this->view('404');
            return;
        }

        // Increment download count
        $stmt = $db->prepare("UPDATE apks SET total_downloads = total_downloads + 1 WHERE id = ?");
        $stmt->execute([$apk['id']]);

        // Referral logic & Anti-Cheat
        $ref_key = 'ref_download_' . $apk['id'];
        
        // If not set for this specific APK, try global referral
        if (!isset($_SESSION[$ref_key]) && isset($_SESSION['global_ref'])) {
            $_SESSION[$ref_key] = $_SESSION['global_ref'];
        }

        if (isset($_SESSION[$ref_key])) {
            $ref_code = $_SESSION[$ref_key];
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            // Find the user who owns this referral code
            $stmt = $db->prepare("SELECT * FROM users WHERE referral_code = ?");
            $stmt->execute([$ref_code]);
            $referrer = $stmt->fetch();

            if ($referrer) {
                // Anti-Cheat: Check if this IP has already downloaded this APK for THIS referrer today
                $stmt = $db->prepare("SELECT COUNT(*) FROM referral_downloads WHERE referrer_id = ? AND apk_id = ? AND ip_address = ? AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)");
                $stmt->execute([$referrer['id'], $apk['id'], $ip_address]);
                $already_downloaded = $stmt->fetchColumn();

                // Anti-Cheat: Check general download frequency from this IP (max 10 rewarded downloads per IP per 24h across all APKs)
                $stmt = $db->prepare("SELECT COUNT(*) FROM referral_downloads WHERE ip_address = ? AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)");
                $stmt->execute([$ip_address]);
                $ip_total_daily = $stmt->fetchColumn();

                if ($already_downloaded == 0 && $ip_total_daily < 10) {
                    // Reward amount
                    $reward_amount = 500.00;

                    // Record the referral download
                    $stmt = $db->prepare("INSERT INTO referral_downloads (referrer_id, apk_id, ip_address, amount) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$referrer['id'], $apk['id'], $ip_address, $reward_amount]);

                    // Award balance to referrer
                    $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                    $stmt->execute([$reward_amount, $referrer['id']]);
                }
            }

            unset($_SESSION[$ref_key]);
        }

        header('Location: ' . $apk['download_url']);
        exit;
    }

    public function helpCenter() {
        $this->view('help_center', [
            'title' => __('help_center') . ' - ' . get_setting('site_name', 'ApkNusa')
        ]);
    }

    public function privacyPolicy() {
        $this->view('privacy_policy', [
            'title' => __('privacy_policy') . ' - ' . get_setting('site_name', 'ApkNusa')
        ]);
    }

    public function termsOfService() {
        $this->view('terms_of_service', [
            'title' => __('terms_of_service') . ' - ' . get_setting('site_name', 'ApkNusa')
        ]);
    }
}