<?php

namespace App\Controllers\View;

use CodeIgniter\Controller;

class FrontendController extends Controller
{
    public function index()
    {
        return view('/index');
    }

    public function facility()
    {
        log_message('debug', 'FrontendController::facility called');
        helper('url'); // Ensure URL helper is loaded
        return view('/facility');
    }

    public function team()
    {
        log_message('debug', 'FrontendController::team called');
        return view('/team');
    }

    public function callToAction()
    {
        log_message('debug', 'FrontendController::callToAction called');
        return view('/call_to_action');
    }

    public function testimonial()
    {
        log_message('debug', 'FrontendController::testimonial called');
        return view('/testimonial');
    }

    public function notFound()
    {
        log_message('debug', 'FrontendController::notFound called');
        return view('/notFound');
    }

    public function fetchUser()
    {
        header('Content-Type: application/json');

        // Include the shared database connection file
        $file = __DIR__ . '/../db_connection.php';

        if (file_exists($file)) {
            require_once $file;
        } else {
            die("Error: Could not find the required file '$file'.");
        }

        // Assuming the logged-in user's information is available in the session
        session_start();
        if (!isset($_SESSION['user_id'])) {
            echo json_encode(['error' => 'User not logged in']);
            exit;
        }

        $userId = $_SESSION['user_id'];

        // Fetch user data from the database
        $sql = "SELECT firstname, lastname FROM users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        if ($user) {
            echo json_encode($user);
        } else {
            echo json_encode(['error' => 'User not found']);
        }

        $stmt->close();
        $conn->close();
    }
}