<?php
require_once APP_PATH . '/Core/BaseController.php';

class ResourceController extends BaseController {

    public function index(): void {
        $db      = Database::getInstance();
        $module  = $_GET['module'] ?? '';
        $category= $_GET['category'] ?? '';

        $sql  = "SELECT r.*, u.first_name, u.last_name FROM resources r LEFT JOIN users u ON u.id = r.author_id WHERE r.is_published = 1";
        $params = [];
        if ($module) { $sql .= " AND r.module = ?"; $params[] = $module; }
        if ($category) { $sql .= " AND r.category = ?"; $params[] = $category; }
        $sql .= " ORDER BY r.is_featured DESC, r.created_at DESC LIMIT 50";

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $resources = $stmt->fetchAll();

        $this->view('resources.index', [
            'title'     => 'Resource Center — BOAFO',
            'resources' => $resources,
            'module'    => $module,
            'category'  => $category,
        ]);
    }

    public function show(string $slug): void {
        $db   = Database::getInstance();
        $stmt = $db->prepare(
            "SELECT r.*, u.first_name, u.last_name FROM resources r
             LEFT JOIN users u ON u.id = r.author_id
             WHERE r.slug = ? AND r.is_published = 1"
        );
        $stmt->execute([$slug]);
        $resource = $stmt->fetch();

        if (!$resource) {
            http_response_code(404);
            $this->view('errors.error', ['title'=>'Not Found','code'=>404,'message'=>'Resource not found.']);
            return;
        }

        $db->prepare("UPDATE resources SET views = views + 1 WHERE slug = ?")->execute([$slug]);

        // Fetch related resources (same category or module, excluding the current one)
        $stmtRel = $db->prepare(
            "SELECT id, title, slug, category FROM resources 
             WHERE id != ? AND is_published = 1 AND (category = ? OR module = ?)
             ORDER BY views DESC LIMIT 5"
        );
        $stmtRel->execute([$resource['id'], $resource['category'], $resource['module']]);
        $relatedResources = $stmtRel->fetchAll();

        $this->view('resources.show', [
            'title'            => $resource['title'] . ' — BOAFO',
            'resource'         => $resource,
            'relatedResources' => $relatedResources,
        ]);
    }

    public function download(string $slug): void {
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT file_path, title FROM resources WHERE slug = ? AND is_published = 1 AND file_path IS NOT NULL");
        $stmt->execute([$slug]);
        $resource = $stmt->fetch();

        if (!$resource) {
            http_response_code(404);
            $this->view('errors.error', ['title' => 'Not Found', 'code' => 404, 'message' => 'Resource file not found.']);
            return;
        }

        $filepath = UPLOAD_PATH . '/resources/' . $resource['file_path'];
        if (file_exists($filepath)) {
            // Increment views/downloads
            $db->prepare("UPDATE resources SET views = views + 1 WHERE slug = ?")->execute([$slug]);
            
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filepath));
            readfile($filepath);
            exit;
        } else {
            http_response_code(404);
            $this->view('errors.error', ['title' => 'Not Found', 'code' => 404, 'message' => 'File is missing on the server.']);
        }
    }
}
