<?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();
    }

    /**
     * List activities with search, filter, and pagination
     */
    public function index()
    {
        $request = $this->request;
        
        $search   = $request->getGet('q');
        $status   = $request->getGet('status');
        $category = $request->getGet('category');
        $sort     = $request->getGet('sort') ?? 'latest';

        $activities = $this->activityModel->getAdminActivities($search, $status, $category, $sort, 10);
        
        // Parse tags
        foreach ($activities as &$activity) {
            $activity['tags_array'] = json_decode($activity['tags'] ?? '[]', true) ?? [];
        }

        $data = [
            'title'      => 'Kelola Aktivitas',
            'activities' => $activities,
            'pager'      => $this->activityModel->pager,
            'categories' => $this->activityModel->getCategories(),
            'search'     => $search,
            'status'     => $status,
            'category'   => $category,
            'sort'       => $sort,
            'total'      => $this->activityModel->countAllResults(false),
        ];

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

    /**
     * Create form
     */
    public function create()
    {
        $data = [
            'title'    => 'Tambah Aktivitas',
            'activity' => null,
        ];

        return view('admin/activities/form', $data);
    }

    /**
     * Store new activity
     */
    public function store()
    {
        $rules = [
            'title'         => 'required|min_length[3]|max_length[200]',
            'category'      => 'required|in_list[Project,Campus,Freelance]',
            'activity_date' => 'permit_empty|valid_date[Y-m-d]',
            'status'        => 'required|in_list[draft,published]',
        ];

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

        $tags = $this->request->getPost('tags');
        $tagsArray = array_map('trim', explode(',', $tags));
        $tagsArray = array_filter($tagsArray);

        $data = [
            'title'         => $this->request->getPost('title'),
            'slug'          => url_title($this->request->getPost('title'), '-', true),
            'description'   => $this->request->getPost('description'),
            'category'      => $this->request->getPost('category'),
            'tags'          => json_encode($tagsArray),
            'activity_date' => $this->request->getPost('activity_date') ?: null,
            'status'        => $this->request->getPost('status'),
        ];

        // Handle cover image upload
        $coverImage = $this->request->getFile('cover_image');
        if ($coverImage && $coverImage->isValid() && !$coverImage->hasMoved()) {
            $validationRules = [
                'cover_image' => [
                    'uploaded[cover_image]',
                    'mime_in[cover_image,image/jpg,image/jpeg,image/png,image/webp]',
                    'max_size[cover_image,4096]',
                ],
            ];

            if ($this->validate($validationRules)) {
                $newName = $coverImage->getRandomName();
                $coverImage->move(WRITEPATH . 'uploads/covers', $newName);
                $data['cover_image'] = 'covers/' . $newName;
            }
        }

        if ($this->activityModel->insert($data)) {
            return redirect()->to('/admin/aktivitas')
                ->with('success', 'Aktivitas berhasil ditambahkan.');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal menambahkan aktivitas.');
    }

    /**
     * Edit form
     */
    public function edit(int $id)
    {
        $activity = $this->activityModel->find($id);

        if (!$activity) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Aktivitas tidak ditemukan');
        }

        $activity['tags_array'] = json_decode($activity['tags'] ?? '[]', true) ?? [];

        $data = [
            'title'    => 'Edit Aktivitas',
            'activity' => $activity,
        ];

        return view('admin/activities/form', $data);
    }

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

        if (!$activity) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Aktivitas tidak ditemukan');
        }

        $rules = [
            'title'         => 'required|min_length[3]|max_length[200]',
            'category'      => 'required|in_list[Project,Campus,Freelance]',
            'activity_date' => 'permit_empty|valid_date[Y-m-d]',
            'status'        => 'required|in_list[draft,published]',
        ];

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

        $tags = $this->request->getPost('tags');
        $tagsArray = array_map('trim', explode(',', $tags));
        $tagsArray = array_filter($tagsArray);

        $data = [
            'title'         => $this->request->getPost('title'),
            'slug'          => url_title($this->request->getPost('title'), '-', true),
            'description'   => $this->request->getPost('description'),
            'category'      => $this->request->getPost('category'),
            'tags'          => json_encode($tagsArray),
            'activity_date' => $this->request->getPost('activity_date') ?: null,
            'status'        => $this->request->getPost('status'),
        ];

        // Handle cover image upload
        $coverImage = $this->request->getFile('cover_image');
        if ($coverImage && $coverImage->isValid() && !$coverImage->hasMoved()) {
            $validationRules = [
                'cover_image' => [
                    'uploaded[cover_image]',
                    'mime_in[cover_image,image/jpg,image/jpeg,image/png,image/webp]',
                    'max_size[cover_image,4096]',
                ],
            ];

            if ($this->validate($validationRules)) {
                // Delete old image if exists
                if ($activity['cover_image'] && file_exists(WRITEPATH . 'uploads/' . $activity['cover_image'])) {
                    unlink(WRITEPATH . 'uploads/' . $activity['cover_image']);
                }
                
                $newName = $coverImage->getRandomName();
                $coverImage->move(WRITEPATH . 'uploads/covers', $newName);
                $data['cover_image'] = 'covers/' . $newName;
            }
        }

        if ($this->activityModel->update($id, $data)) {
            return redirect()->to('/admin/aktivitas')
                ->with('success', 'Aktivitas berhasil diperbarui.');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal memperbarui aktivitas.');
    }

    /**
     * Delete activity
     */
    public function delete(int $id)
    {
        $activity = $this->activityModel->find($id);

        if (!$activity) {
            return redirect()->to('/admin/aktivitas')
                ->with('error', 'Aktivitas tidak ditemukan.');
        }

        // Delete cover image if exists
        if ($activity['cover_image'] && file_exists(WRITEPATH . 'uploads/' . $activity['cover_image'])) {
            unlink(WRITEPATH . 'uploads/' . $activity['cover_image']);
        }

        if ($this->activityModel->delete($id)) {
            return redirect()->to('/admin/aktivitas')
                ->with('success', 'Aktivitas berhasil dihapus.');
        }

        return redirect()->to('/admin/aktivitas')
            ->with('error', 'Gagal menghapus aktivitas.');
    }
}
