<?php

namespace Modules\Inventory\Controllers;

use core\Controller;
use core\Auth;
use core\Database;

class SupplierController extends Controller
{
    public function index(): void
    {
        $this->requirePermission('suppliers_view');

        $search = $this->request->get('search', '');
        $status = $this->request->get('status', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;
        $db = Database::getInstance();

        $query = $db->table('suppliers')
            ->where('deleted_at', 'IS', null);

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'LIKE', '%' . $search . '%')
                  ->orWhere('contact_person', 'LIKE', '%' . $search . '%')
                  ->orWhere('email', 'LIKE', '%' . $search . '%')
                  ->orWhere('phone', 'LIKE', '%' . $search . '%')
                  ->orWhere('mobile', 'LIKE', '%' . $search . '%');
            });
        }

        if ($status === 'active') {
            $query->where('is_active', 1);
        } elseif ($status === 'inactive') {
            $query->where('is_active', 0);
        }

        $suppliers = $query->orderBy('name', 'ASC')
            ->paginate($perPage, $page);

        $this->view('Inventory/suppliers/index', [
            'title' => 'Suppliers',
            'breadcrumb' => ['Suppliers' => url('suppliers')],
            'suppliers' => $suppliers,
            'search' => $search,
            'status' => $status,
        ]);
    }

    public function create(): void
    {
        $this->requirePermission('suppliers_create');

        $this->view('Inventory/suppliers/create', [
            'title' => 'Add New Supplier',
            'breadcrumb' => [
                'Suppliers' => url('suppliers'),
                'Add New' => url('suppliers/create'),
            ],
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('suppliers_create');

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'contact_person' => 'max_length:255',
            'email' => 'email|max_length:255',
            'phone' => 'max_length:20',
            'mobile' => 'max_length:20',
            'address' => 'max_length:500',
            'city' => 'max_length:100',
            'state' => 'max_length:100',
            'tax_id' => 'max_length:100',
            'payment_terms' => 'max_length:255',
            'notes' => 'max_length:2000',
            'is_active' => 'in:0,1',
        ]);

        $validated['is_active'] = $validated['is_active'] ?? 1;

        $db = Database::getInstance();
        $supplierId = $db->table('suppliers')->insert([
            'name' => $validated['name'],
            'contact_person' => $validated['contact_person'] ?? '',
            'email' => $validated['email'] ?? '',
            'phone' => $validated['phone'] ?? '',
            'mobile' => $validated['mobile'] ?? '',
            'address' => $validated['address'] ?? '',
            'city' => $validated['city'] ?? '',
            'state' => $validated['state'] ?? '',
            'tax_id' => $validated['tax_id'] ?? '',
            'payment_terms' => $validated['payment_terms'] ?? '',
            'notes' => $validated['notes'] ?? '',
            'is_active' => $validated['is_active'],
            'created_at' => date(DATE_TIME_FORMAT),
            'updated_at' => date(DATE_TIME_FORMAT),
        ]);

        $this->logActivity('create', 'Created supplier: ' . ($validated['name'] ?? ''));
        $this->logAudit('create', 'suppliers', $supplierId, null, $validated);

        $this->redirectWith(url('suppliers'), 'success', 'Supplier created successfully.');
    }

    public function edit(int $id): void
    {
        $this->requirePermission('suppliers_edit');

        $db = Database::getInstance();
        $supplier = $db->table('suppliers')
            ->where('id', $id)
            ->where('deleted_at', 'IS', null)
            ->first();

        if (!$supplier) {
            $this->redirectWith(url('suppliers'), 'error', 'Supplier not found.');
        }

        $this->view('Inventory/suppliers/edit', [
            'title' => 'Edit Supplier',
            'breadcrumb' => [
                'Suppliers' => url('suppliers'),
                'Edit' => url('suppliers/edit/' . $id),
            ],
            'supplier' => $supplier,
        ]);
    }

    public function update(int $id): void
    {
        $this->requirePermission('suppliers_edit');

        $db = Database::getInstance();
        $supplier = $db->table('suppliers')
            ->where('id', $id)
            ->where('deleted_at', 'IS', null)
            ->first();

        if (!$supplier) {
            $this->redirectWith(url('suppliers'), 'error', 'Supplier not found.');
        }

        $oldValues = (array)$supplier;

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'contact_person' => 'max_length:255',
            'email' => 'email|max_length:255',
            'phone' => 'max_length:20',
            'mobile' => 'max_length:20',
            'address' => 'max_length:500',
            'city' => 'max_length:100',
            'state' => 'max_length:100',
            'tax_id' => 'max_length:100',
            'payment_terms' => 'max_length:255',
            'notes' => 'max_length:2000',
            'is_active' => 'in:0,1',
        ]);

        $validated['is_active'] = $validated['is_active'] ?? 0;

        $db->table('suppliers')
            ->where('id', $id)
            ->update([
                'name' => $validated['name'],
                'contact_person' => $validated['contact_person'] ?? '',
                'email' => $validated['email'] ?? '',
                'phone' => $validated['phone'] ?? '',
                'mobile' => $validated['mobile'] ?? '',
                'address' => $validated['address'] ?? '',
                'city' => $validated['city'] ?? '',
                'state' => $validated['state'] ?? '',
                'tax_id' => $validated['tax_id'] ?? '',
                'payment_terms' => $validated['payment_terms'] ?? '',
                'notes' => $validated['notes'] ?? '',
                'is_active' => $validated['is_active'],
                'updated_at' => date(DATE_TIME_FORMAT),
            ]);

        $this->logActivity('update', 'Updated supplier: ' . ($validated['name'] ?? ''));
        $this->logAudit('update', 'suppliers', $id, $oldValues, $validated);

        $this->redirectWith(url('suppliers'), 'success', 'Supplier updated successfully.');
    }

    public function delete(int $id): void
    {
        $this->requirePermission('suppliers_delete');

        $db = Database::getInstance();
        $supplier = $db->table('suppliers')
            ->where('id', $id)
            ->where('deleted_at', 'IS', null)
            ->first();

        if (!$supplier) {
            $this->redirectWith(url('suppliers'), 'error', 'Supplier not found.');
        }

        $db->table('suppliers')
            ->where('id', $id)
            ->update([
                'deleted_at' => date(DATE_TIME_FORMAT),
            ]);

        $this->logActivity('delete', 'Deleted supplier: ' . $supplier->name);
        $this->logAudit('delete', 'suppliers', $id, (array)$supplier, null);

        $this->redirectWith(url('suppliers'), 'success', 'Supplier deleted successfully.');
    }
}
