<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\CustomerDocumentModel;
use App\Models\CustomerHistoryModel;
use CodeIgniter\HTTP\Files\UploadedFile;
use Config\Uploads;

class CustomerDocumentService
{
    protected CustomerDocumentModel $documents;
    protected CompanyModel $companies;
    protected CustomerHistoryModel $history;
    protected ActivityLogModel $activity;
    protected Uploads $uploadsConfig;

    public function __construct()
    {
        $this->documents     = new CustomerDocumentModel();
        $this->companies     = new CompanyModel();
        $this->history       = new CustomerHistoryModel();
        $this->activity      = new ActivityLogModel();
        $this->uploadsConfig = config('Uploads');
    }

    public function create(array $input, ?UploadedFile $file, ?int $actingUserId): array
    {
        if (! $file || ! $file->isValid() || $file->hasMoved()) {
            return ['success' => false, 'errors' => ['document_file' => 'A document file is required.']];
        }

        $companyId = (int) ($input['company_id'] ?? 0);
        if (! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

        $upload = $this->storeFile($file);
        if (! $upload['success']) {
            return ['success' => false, 'errors' => ['document_file' => $upload['error']]];
        }

        $data = [
            'company_id'        => $companyId,
            'title'             => trim($input['title']),
            'category'          => trim($input['category'] ?? '') ?: null,
            'file_path'         => $upload['path'],
            'original_filename' => $upload['original'],
            'file_size'         => $upload['size'],
            'mime_type'         => $upload['mime'],
            'notes'             => $input['notes'] ?: null,
            'status'            => $input['status'] ?? 'active',
            'created_by'        => $actingUserId,
            'updated_by'        => $actingUserId,
        ];

        if (! $this->documents->insert($data, true)) {
            $this->removeFile($upload['path']);

            return ['success' => false, 'errors' => $this->documents->errors()];
        }

        $id = $this->documents->getInsertID();
        $this->activity->log('customer_documents', 'created', $actingUserId, "Uploaded customer document #{$id}", (string) $id);
        $this->history->insert([
            'company_id'  => $companyId,
            'event_type'  => 'document',
            'title'       => 'Document uploaded: ' . $data['title'],
            'description' => $data['original_filename'],
            'event_at'    => date('Y-m-d H:i:s'),
            'created_by'  => $actingUserId,
        ]);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $document = $this->documents->find($id);
        if (! $document) {
            return ['success' => false, 'errors' => ['id' => 'Document not found.']];
        }

        $companyId = (int) ($input['company_id'] ?? $document['company_id']);
        if (! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

        $data = [
            'company_id' => $companyId,
            'title'      => trim($input['title']),
            'category'   => trim($input['category'] ?? '') ?: null,
            'notes'      => $input['notes'] ?: null,
            'status'     => $input['status'] ?? $document['status'],
            'updated_by' => $actingUserId,
        ];

        if (! $this->documents->update($id, $data)) {
            return ['success' => false, 'errors' => $this->documents->errors()];
        }

        $this->activity->log('customer_documents', 'updated', $actingUserId, "Updated customer document #{$id}", (string) $id);

        return ['success' => true];
    }

    public function archive(int $id, ?int $actingUserId): void
    {
        $this->documents->update($id, ['status' => 'archived', 'updated_by' => $actingUserId]);
        $this->activity->log('customer_documents', 'archived', $actingUserId, "Archived customer document #{$id}", (string) $id);
    }

    public function restore(int $id, ?int $actingUserId): void
    {
        $this->documents->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('customer_documents', 'restored', $actingUserId, "Restored customer document #{$id}", (string) $id);
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $document = $this->documents->find($id);
        if (! $document) {
            return ['success' => false, 'error' => 'Document not found.'];
        }

        $this->removeFile($document['file_path']);
        $this->documents->delete($id);
        $this->activity->log('customer_documents', 'deleted', $actingUserId, "Deleted customer document #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function storeFile(UploadedFile $file): array
    {
        $ext = strtolower($file->getClientExtension() ?: '');
        if (! in_array($ext, $this->uploadsConfig->customerDocumentAllowedExt, true)) {
            return ['success' => false, 'error' => 'File type not allowed.'];
        }

        if ($file->getSizeByUnit('kb') > $this->uploadsConfig->customerDocumentMaxSizeKB) {
            return ['success' => false, 'error' => 'File exceeds maximum size.'];
        }

        $dir = $this->uploadsConfig->customerDocumentUploadPath;
        if (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir)) {
            return ['success' => false, 'error' => 'Unable to create upload directory.'];
        }

        $newName = $file->getRandomName();
        $original = $file->getClientName();
        $size     = (int) $file->getSize();
        $mime     = $file->getClientMimeType() ?: $file->getMimeType();
        if (! $file->move($dir, $newName)) {
            return ['success' => false, 'error' => 'Failed to store uploaded file.'];
        }

        return [
            'success'  => true,
            'path'     => rtrim($this->uploadsConfig->customerDocumentPublicPath, '/') . '/' . $newName,
            'original' => $original,
            'size'     => $size,
            'mime'     => $mime,
        ];
    }

    protected function removeFile(string $relativePath): void
    {
        $full = FCPATH . ltrim(str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relativePath), DIRECTORY_SEPARATOR);
        if (is_file($full)) {
            @unlink($full);
        }
    }
}
