<?php

namespace Modules\Contracts\Controllers;

use App\Controllers\BaseController;
use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\ContactModel;
use App\Models\CustomerSiteModel;
use Modules\Contracts\Services\SiteService;

class SiteController extends BaseController
{
    protected CustomerSiteModel $sites;
    protected CompanyModel $companies;
    protected ContactModel $contacts;
    protected ActivityLogModel $activity;
    protected SiteService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->sites     = new CustomerSiteModel();
        $this->companies = new CompanyModel();
        $this->contacts  = new ContactModel();
        $this->activity  = new ActivityLogModel();
        $this->service   = new SiteService();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $sites = $this->sites
            ->scopeForList($search ?: null, $status)
            ->orderBy('name', 'ASC')
            ->paginate(25);

        $siteIds = array_map(static fn (array $site): int => (int) $site['id'], $sites);
        $counts  = $this->sites->countCustomersForSites($siteIds);

        return view('Modules\Contracts\Views\sites\index', array_merge($this->baseViewData(), [
            'title'   => 'Customer Sites',
            'sites'   => $sites,
            'counts'  => $counts,
            'pager'   => $this->sites->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function details()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $sites = $this->sites
            ->scopeForList($search ?: null, $status)
            ->orderBy('name', 'ASC')
            ->paginate(25);

        $siteIds = array_map(static fn (array $site): int => (int) $site['id'], $sites);
        $counts  = $this->sites->countCustomersForSites($siteIds);

        return view('Modules\Contracts\Views\sites\details', array_merge($this->baseViewData(), [
            'title'   => 'Site Details',
            'sites'   => $sites,
            'counts'  => $counts,
            'pager'   => $this->sites->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function contacts()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;
        $siteId = $this->request->getGet('site_id') ?: null;

        $builder = $this->contacts
            ->select('contacts.*, companies.name AS company_name, companies.site_id, customer_sites.name AS site_name')
            ->join('companies', 'companies.id = contacts.company_id')
            ->join('customer_sites', 'customer_sites.id = companies.site_id')
            ->where('companies.site_id IS NOT NULL');

        if ($search !== '') {
            $builder->groupStart()
                ->like('contacts.first_name', $search)
                ->orLike('contacts.last_name', $search)
                ->orLike('contacts.email', $search)
                ->orLike('contacts.phone', $search)
                ->orLike('companies.name', $search)
                ->orLike('customer_sites.name', $search)
                ->groupEnd();
        }

        if ($status) {
            $builder->where('contacts.status', $status);
        }

        if ($siteId) {
            $builder->where('companies.site_id', (int) $siteId);
        }

        $rows = $builder
            ->orderBy('customer_sites.name', 'ASC')
            ->orderBy('companies.name', 'ASC')
            ->orderBy('contacts.last_name', 'ASC')
            ->paginate(25);

        return view('Modules\Contracts\Views\sites\contacts', array_merge($this->baseViewData(), [
            'title'    => 'Site Contacts',
            'contacts' => $rows,
            'pager'    => $this->contacts->pager,
            'sites'    => $this->sites->getActive($search !== '' ? $search : null, 100),
            'filters'  => [
                'search' => $search,
                'status' => $status,
                'siteId' => $siteId,
            ],
        ]));
    }

    public function history()
    {
        $search = trim((string) $this->request->getGet('q'));
        $siteId = $this->request->getGet('site_id') ?: null;

        $builder = $this->activity
            ->select('activity_logs.*, customer_sites.name AS site_name')
            ->join('customer_sites', 'customer_sites.id = activity_logs.record_id', 'left')
            ->where('activity_logs.module', 'customer_sites');

        if ($search !== '') {
            $builder->groupStart()
                ->like('activity_logs.description', $search)
                ->orLike('activity_logs.action', $search)
                ->orLike('customer_sites.name', $search)
                ->groupEnd();
        }

        if ($siteId) {
            $builder->where('activity_logs.record_id', (string) (int) $siteId);
        }

        $entries = $builder
            ->orderBy('activity_logs.created_at', 'DESC')
            ->orderBy('activity_logs.id', 'DESC')
            ->paginate(25);

        return view('Modules\Contracts\Views\sites\history', array_merge($this->baseViewData(), [
            'title'   => 'Site History',
            'entries' => $entries,
            'pager'   => $this->activity->pager,
            'sites'   => $this->sites->getActive($search !== '' ? $search : null, 100),
            'filters' => [
                'search' => $search,
                'siteId' => $siteId,
            ],
        ]));
    }

    public function createForm()
    {
        return view('Modules\Contracts\Views\sites\create', array_merge($this->baseViewData(), [
            'title' => 'Add Customer Site',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
            'code' => 'required|max_length[30]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/contracts/sites/' . $result['id'])->with('success', 'Site created.');
    }

    public function show(int $id)
    {
        $site = $this->sites->find($id);
        if (! $site) {
            return redirect()->to('/contracts/sites')->with('error', 'Site not found.');
        }

        $customers = $this->companies
            ->where('site_id', $id)
            ->orderBy('name', 'ASC')
            ->findAll();

        $available = $this->companies
            ->where('status', 'active')
            ->groupStart()
                ->where('site_id', null)
                ->orWhere('site_id !=', $id)
            ->groupEnd()
            ->orderBy('name', 'ASC')
            ->limit(100)
            ->findAll();

        return view('Modules\Contracts\Views\sites\show', array_merge($this->baseViewData(), [
            'title'     => $site['name'],
            'site'      => $site,
            'customers' => $customers,
            'available' => $available,
        ]));
    }

    public function assignCustomer(int $id)
    {
        if (! $this->validate([
            'company_id' => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->with('error', 'Please select a customer to assign.');
        }

        $result = $this->service->assignCustomer(
            $id,
            (int) $this->request->getPost('company_id'),
            (int) $this->session->get('user_id')
        );

        if (! $result['success']) {
            return redirect()->to('/contracts/sites/' . $id)->with('error', $result['error']);
        }

        return redirect()->to('/contracts/sites/' . $id)->with('success', 'Customer assigned to this site.');
    }

    public function unassignCustomer(int $id, int $companyId)
    {
        $result = $this->service->unassignCustomer($id, $companyId, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/contracts/sites/' . $id)->with('error', $result['error']);
        }

        return redirect()->to('/contracts/sites/' . $id)->with('success', 'Customer removed from this site.');
    }

    public function editForm(int $id)
    {
        $site = $this->sites->find($id);
        if (! $site) {
            return redirect()->to('/contracts/sites')->with('error', 'Site not found.');
        }

        return view('Modules\Contracts\Views\sites\edit', array_merge($this->baseViewData(), [
            'title' => 'Edit Customer Site',
            'site'  => $site,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
            'code' => 'required|max_length[30]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/contracts/sites/' . $id)->with('success', 'Site updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Site activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Site deactivated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/contracts/sites')->with('error', $result['error']);
        }

        return redirect()->to('/contracts/sites')->with('success', 'Site deleted.');
    }
}
