<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ActivityModel;

class ActivityController extends BaseController
{
    protected $activityModel;

    public function __construct()
    {
        $this->activityModel = new ActivityModel();
    }

    public function index()
    {
        $search = $this->request->getGet('search');
        $date = $this->request->getGet('date');
        $type = $this->request->getGet('type'); // all, with_media, no_media
        $sort = $this->request->getGet('sort') ?? 'newest'; // newest, oldest
        $order = $this->request->getGet('order') ?? 'DESC';

        $activities = $this->activityModel;

        // Search
        if ($search) {
            $activities = $activities->like('activity', $search);
        }

        // Filter by Date
        if ($date) {
            $activities = $activities->where('date', $date);
        }

        // Filter by Type (Media presence)
        if ($type === 'with_media') {
            $activities = $activities->where('media !=', null)->where('media !=', '');
        } elseif ($type === 'no_media') {
            $activities = $activities->groupStart()->where('media', null)->orWhere('media', '')->groupEnd();
        }

        // Sorting
        $allowedColumns = ['date', 'time', 'activity', 'media'];

        if (in_array($sort, $allowedColumns)) {
            $activities = $activities->orderBy($sort, $order);
        } elseif ($sort === 'oldest') {
            $activities = $activities->orderBy('date', 'ASC')->orderBy('time', 'ASC');
        } else {
            // Default newest
            $activities = $activities->orderBy('date', 'DESC')->orderBy('time', 'DESC');
        }

        $data = [
            'activities' => $activities->paginate(10),
            'pager' => $this->activityModel->pager,
            'search' => $search,
            'date' => $date,
            'type' => $type,
            'sort' => $sort,
            'order' => $order, // Pass order back for table headers
        ];

        return view('admin/activity/index', $data);
    }

    public function new()
    {
        return view('admin/activity/form', ['title' => 'New Activity']);
    }

    public function create()
    {
        $rules = [
            'date' => 'required|valid_date',
            'time' => 'required',
            'activity' => 'required|min_length[3]',
            'media' => 'uploaded[media]|max_size[media,10240]|is_image[media]', // Basic validation
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $file = $this->request->getFile('media');
        $fileName = null;

        if ($file->isValid() && !$file->hasMoved()) {
            $fileName = $file->getRandomName();
            $file->move(FCPATH . 'uploads', $fileName);
        }

        $this->activityModel->save([
            'date' => $this->request->getPost('date'),
            'time' => $this->request->getPost('time'),
            'activity' => $this->request->getPost('activity'),
            'media' => $fileName,
        ]);

        return redirect()->to('/admin/activities')->with('message', 'Activity created successfully');
    }

    public function edit($id)
    {
        $activity = $this->activityModel->find($id);
        if (!$activity) {
            return redirect()->to('/admin/activities')->with('error', 'Activity not found');
        }

        return view('admin/activity/form', ['activity' => $activity, 'title' => 'Edit Activity']);
    }

    public function update($id)
    {
        $activity = $this->activityModel->find($id);

        // Validation without mandatory file
        $rules = [
            'date' => 'required|valid_date',
            'time' => 'required',
            'activity' => 'required|min_length[3]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = [
            'id' => $id,
            'date' => $this->request->getPost('date'),
            'time' => $this->request->getPost('time'),
            'activity' => $this->request->getPost('activity'),
        ];

        $file = $this->request->getFile('media');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $fileName = $file->getRandomName();
            $file->move(FCPATH . 'uploads', $fileName);
            $data['media'] = $fileName;
        }

        $this->activityModel->save($data);

        return redirect()->to('/admin/activities')->with('message', 'Activity updated successfully');
    }

    public function delete($id)
    {
        $this->activityModel->delete($id);
        return redirect()->to('/admin/activities')->with('message', 'Activity deleted successfully');
    }
}
