<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\TestimonialModel;

class TestimonialController extends BaseController
{
    public function index()
    {
        $testimonials = (new TestimonialModel())->forCompany($this->currentCompanyId())->orderBy('created_at', 'DESC')->findAll();
        return view('admin/site_testimonials/index', ['testimonials' => $testimonials]);
    }

    public function create()
    {
        return view('admin/site_testimonials/form', ['testimonial' => null]);
    }

    public function store()
    {
        $data = $this->testimonialData();
        $data['company_id'] = $this->currentCompanyId();
        $data['photo'] = $this->handlePhotoUpload();

        (new TestimonialModel())->insert($data);
        return redirect()->to('/admin/site-testimonials')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $testimonial = (new TestimonialModel())->forCompany($this->currentCompanyId())->find($id);
        if (! $testimonial) return redirect()->to('/admin/site-testimonials');
        return view('admin/site_testimonials/form', ['testimonial' => $testimonial]);
    }

    public function update($id)
    {
        $data = $this->testimonialData();
        $photo = $this->handlePhotoUpload();
        if ($photo) $data['photo'] = $photo;

        (new TestimonialModel())->update($id, $data);
        return redirect()->to('/admin/site-testimonials')->with('message', lang('App.saved_successfully'));
    }

    public function delete($id)
    {
        (new TestimonialModel())->delete($id);
        return redirect()->to('/admin/site-testimonials')->with('message', lang('App.deleted_successfully'));
    }

    private function testimonialData(): array
    {
        return [
            'client_name' => $this->request->getPost('client_name'),
            'content' => $this->request->getPost('content'),
            'rating' => $this->request->getPost('rating') ?: 5,
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ];
    }

    private function handlePhotoUpload(): ?string
    {
        $file = $this->request->getFile('photo');
        if (! $file || ! $file->isValid() || $file->hasMoved()) return null;

        if (! is_dir(FCPATH . 'uploads/testimonials')) {
            mkdir(FCPATH . 'uploads/testimonials', 0755, true);
        }
        $newName = 'testimonial_' . time() . '_' . rand(100, 999) . '.' . $file->getExtension();
        $file->move(FCPATH . 'uploads/testimonials', $newName);
        return $newName;
    }
}
