<?php
namespace Modules\Clients\Controllers;

use Core\Controller;
use Core\Auth;
use Modules\Clients\Models\ClientModel;

class ClientController extends Controller {
    private $clientModel;

    public function __construct() {
        parent::__construct();
        $this->clientModel = new ClientModel();
    }

    public function index() {
        $this->requireAuth();
        $orgId = $this->scopedOrgId();
        $page = max(1, (int)$this->getGet('page', 1));
        $perPage = 20;
        $filters = [
            'search' => $this->getGet('search', ''),
            'industry' => $this->getGet('industry', ''),
        ];

        $clients = $this->clientModel->getAllForOrg($orgId, $filters, $page, $perPage);
        $total = $this->clientModel->countForOrg($orgId, $filters);
        $stats = $this->clientModel->getStats($orgId);

        $paginationData = [
            'current_page' => $page,
            'total_pages' => (int)ceil($total / $perPage),
            'total_items' => $total,
            'url_pattern' => APP_URL . '/clients?' . http_build_query(array_filter($filters)) . '&page=',
        ];

        $this->render('clients/index', [
            'clients' => $clients,
            'stats' => $stats,
            'filters' => $filters,
            'isPlatformView' => $orgId === null,
            'paginationData' => $paginationData,
        ]);
    }

    public function create() {
        $this->requireAuth();
        if (Auth::orgId() === null) {
            $this->setFlash('error', 'Clients belong to an organization. Log in as an organization user to create one.');
            $this->redirect('/clients');
        }
        $this->render('clients/create');
    }

    public function store() {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/clients/create');
        }
        if (Auth::orgId() === null) {
            $this->setFlash('error', 'Clients belong to an organization. Log in as an organization user to create one.');
            $this->redirect('/clients');
        }

        $data = $this->buildClientData($_POST);
        if (empty($data['company_name'])) {
            $this->setFlash('error', 'Company name is required.');
            $this->redirect('/clients/create');
        }

        $data['org_id'] = Auth::orgId();
        $data['created_by'] = Auth::id();
        $data['client_code'] = $this->clientModel->generateClientCode();

        $id = $this->clientModel->create($data);
        logAudit('client_created', 'clients', 'client', $id, null, $data);
        $this->setFlash('success', 'Client created successfully.');
        $this->redirect('/clients/' . $id);
    }

    public function show($id) {
        $this->requireAuth();
        $client = $this->clientModel->getWithProjects((int)$id);
        if (!$client || (int)$client['org_id'] !== (int)Auth::orgId()) {
            $this->setFlash('error', 'Client not found.');
            $this->redirect('/clients');
        }
        $this->render('clients/show', ['client' => $client]);
    }

    public function edit($id) {
        $this->requireAuth();
        $client = $this->clientModel->getWithProjects((int)$id);
        if (!$client || (int)$client['org_id'] !== (int)Auth::orgId()) {
            $this->setFlash('error', 'Client not found.');
            $this->redirect('/clients');
        }
        $this->render('clients/create', ['client' => $client]);
    }

    public function update($id) {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/clients/' . $id . '/edit');
        }

        $client = $this->clientModel->find((int)$id);
        if (!$client || (int)$client['org_id'] !== (int)Auth::orgId()) {
            $this->setFlash('error', 'Client not found.');
            $this->redirect('/clients');
        }

        $data = $this->buildClientData($_POST);
        if (empty($data['company_name'])) {
            $this->setFlash('error', 'Company name is required.');
            $this->redirect('/clients/' . $id . '/edit');
        }

        $this->clientModel->update((int)$id, $data);
        logAudit('client_updated', 'clients', 'client', (int)$id, $client, $data);
        $this->setFlash('success', 'Client updated successfully.');
        $this->redirect('/clients/' . $id);
    }

    public function delete($id) {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/clients');
        }

        $client = $this->clientModel->find((int)$id);
        if (!$client || (int)$client['org_id'] !== (int)Auth::orgId()) {
            $this->setFlash('error', 'Client not found.');
            $this->redirect('/clients');
        }

        if ($this->clientModel->hasProjects((int)$id)) {
            $this->setFlash('error', 'Cannot delete a client that has projects. Deactivate it instead.');
            $this->redirect('/clients');
        }

        $this->clientModel->delete((int)$id);
        logAudit('client_deleted', 'clients', 'client', (int)$id);
        $this->setFlash('success', 'Client deleted successfully.');
        $this->redirect('/clients');
    }

    private function buildClientData(array $post): array {
        return [
            'company_name' => trim($post['company_name'] ?? ''),
            'industry' => $post['industry'] ?? null,
            'tin' => $post['tin'] ?? null,
            'address' => $post['address'] ?? null,
            'phone' => $post['phone'] ?? null,
            'email' => $post['email'] ?? null,
            'website' => normalizeUrl($post['website'] ?? null),
            'contact_person_name' => $post['contact_name'] ?? null,
            'contact_person_phone' => $post['contact_phone'] ?? null,
            'contact_person_email' => $post['contact_email'] ?? null,
        ];
    }
}
