<?php

namespace App\Controllers;

class Page extends BaseController
{
    public function about()
    {
        $request = \Config\Services::request();
        $search = $request->getGet('q');
        $religion_filter = $request->getGet('religion_filter');

        $biodataModel = new \App\Models\BiodataModel();
        // Fetch all biodata entries (assuming one or list)
        $data_bio = $biodataModel->findAll();

        // 1. Search Filter
        if ($search) {
            $data_bio = array_filter($data_bio, function ($item) use ($search) {
                return (isset($item['name']) && stripos($item['name'], $search) !== false) ||
                    (isset($item['address']) && stripos($item['address'], $search) !== false) ||
                    (isset($item['email']) && stripos($item['email'], $search) !== false);
            });
        }

        // 2. Religion Filter (Note: DB column for religion might need to be added if not present, assuming 'summary' or other field for now or skipping if column doesn't exist)
        // If the column 'religion' doesn't exist in DB, this filter won't work as expected. 
        // For now, removing strict religion filter or mapping it if we add the column.
        // As per migration, we don't have 'religion' column. We can add it or just ignore for now.

        // 3. Pagination
        $perPage = 6; // Set items per page
        $page = (int) ($request->getGet('page') ?? 1);
        $total = count($data_bio);
        $totalPages = ceil($total / $perPage);
        $page = max(1, min($page, $totalPages > 0 ? $totalPages : 1));
        $offset = ($page - 1) * $perPage;
        $display_data = array_slice($data_bio, $offset, $perPage);

        $data = [
            "biodata" => $display_data,
            "search" => $search,
            "religion_filter" => $religion_filter,
            "page" => $page,
            "totalPages" => $totalPages
        ];

        echo view("about_page", $data);
    }

    public function education()
    {
        $request = \Config\Services::request();
        $search = $request->getGet('q');
        $level_filter = $request->getGet('level_filter');
        $year_filter = $request->getGet('year_filter');
        $sort = $request->getGet('sort') ?? 'year';
        $order = $request->getGet('order') ?? 'desc';
        $page = (int) ($request->getGet('page') ?? 1);
        $perPage = 10;

        $educationModel = new \App\Models\EducationModel();
        $data_edu = $educationModel->findAll();

        // Map DB columns to View expectations if needed, or update View.
        // View expects: 'school', 'year_start', 'year_end', 'level'
        // DB has: 'institution', 'start_year', 'end_year', 'degree'
        // We will map them for compatibility with existing view logic temporarily OR update View. 
        // Better to mapped array here to convert DB keys to View keys for minimal breakage.

        $data_edu_mapped = array_map(function ($item) {
            return [
                'school' => $item['institution'],
                'year_start' => $item['start_year'],
                'year_end' => $item['end_year'],
                'level' => $item['degree'],
                'description' => $item['description'] ?? ''
            ];
        }, $data_edu);

        $data_edu = $data_edu_mapped;

        // Extract Unique Years for Dropdown
        $unique_years = array_unique(array_column($data_edu, 'year_start'));
        rsort($unique_years);

        // 1. Search Filter
        if ($search) {
            $data_edu = array_filter($data_edu, function ($item) use ($search) {
                return stripos($item['school'], $search) !== false || stripos($item['level'], $search) !== false;
            });
        }

        // 2. Level Filter
        if ($level_filter && $level_filter != 'Semua') {
            $data_edu = array_filter($data_edu, function ($item) use ($level_filter) {
                $map = [
                    'SD' => 'Sekolah Dasar',
                    'SMP' => 'Sekolah Menengah Pertama',
                    'SMA' => 'Sekolah Menengah Atas',
                    'SMK' => 'Sekolah Menengah Kejuruan',
                    'D3' => 'Diploma 3',
                    'S1' => 'Sarjana (S1)',
                    'S2' => 'Magister',
                    'S3' => 'Doktor'
                ];
                $keyword = $map[$level_filter] ?? $level_filter;
                return stripos($item['level'], $keyword) !== false;
            });
        }

        // 3. Year Filter
        if ($year_filter && $year_filter != 'Semua') {
            $data_edu = array_filter($data_edu, function ($item) use ($year_filter) {
                return $item['year_start'] == $year_filter;
            });
        }

        // 4. Sorting
        usort($data_edu, function ($a, $b) use ($sort, $order) {
            if ($sort == 'name') {
                return $order == 'asc' ? strcasecmp($a['school'], $b['school']) : strcasecmp($b['school'], $a['school']);
            } elseif ($sort == 'level') {
                return 0; // Simplified
            } else {
                if ($a['year_start'] == $b['year_start'])
                    return 0;
                return $order == 'asc' ? ($a['year_start'] - $b['year_start']) : ($b['year_start'] - $a['year_start']);
            }
        });

        // 3. Pagination
        $total = count($data_edu);
        $totalPages = ceil($total / $perPage);
        $page = max(1, min($page, $totalPages > 0 ? $totalPages : 1));
        $offset = ($page - 1) * $perPage;
        $display_data = array_slice($data_edu, $offset, $perPage);

        $data = [
            "name" => "Universitas Yatsi Madani",
            "education" => $display_data,
            "search" => $search,
            "level_filter" => $level_filter,
            "year_filter" => $year_filter,
            "unique_years" => $unique_years,
            "sort" => $sort,
            "order" => $order,
            "page" => $page,
            "totalPages" => $totalPages
        ];

        echo view("education_page", $data);
    }

    public function aktivitas()
    {
        $request = \Config\Services::request();
        $search = $request->getGet('q');
        $date_filter = $request->getGet('date');
        $page = (int) ($request->getGet('page') ?? 1);
        $perPage = 6; // Set items per page

        $activityModel = new \App\Models\ActivityModel();
        $activities_db = $activityModel->orderBy('date_activity', 'DESC')->findAll();

        // Convert to View expectations
        $activities = array_map(function ($item) {
            $days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
            $dayName = $days[date('w', strtotime($item['date_activity']))];

            return [
                'day' => $dayName,
                'date' => date('d F Y', strtotime($item['date_activity'])),
                'date_iso' => $item['date_activity'],
                'time' => date('H:i', strtotime($item['time_activity'])),
                'name' => $item['title'],
                'description' => $item['description'],
                'image' => $item['image']
            ];
        }, $activities_db);


        // 1. Search Filter
        if ($search) {
            $activities = array_filter($activities, function ($item) use ($search) {
                return stripos($item['name'], $search) !== false ||
                    stripos($item['description'], $search) !== false;
            });
        }

        // 2. Date Filter
        if ($date_filter) {
            $activities = array_filter($activities, function ($item) use ($date_filter) {
                return $item['date_iso'] == $date_filter;
            });
        }

        // 3. Pagination
        $total = count($activities);
        $totalPages = ceil($total / $perPage);
        $page = max(1, min($page, $totalPages > 0 ? $totalPages : 1));
        $offset = ($page - 1) * $perPage;
        $display_activities = array_slice($activities, $offset, $perPage);

        $data = [
            'activities' => $display_activities,
            'search' => $search,
            'date_filter' => $date_filter,
            'page' => $page,
            'totalPages' => $totalPages
        ];

        echo view('activities_page', $data);
    }
}

