<?php
class SupplierController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('suppliers.view');

        $search  = trim($this->get('search', ''));
        $status  = $this->get('status',  'active');
        $balance = $this->get('balance', 'all'); // all | due | clear

        $where  = ['1=1'];
        $params = [];

        if ($search) {
            $where[]  = '(s.supplier_name LIKE ? OR s.phone LIKE ? OR s.email LIKE ? OR s.contact_person LIKE ?)';
            $params[] = "%$search%"; $params[] = "%$search%";
            $params[] = "%$search%"; $params[] = "%$search%";
        }
        if ($status !== 'all') {
            $where[]  = 's.status = ?';
            $params[] = $status;
        }
        if ($balance === 'due') {
            $where[] = 's.current_balance > 0';
        } elseif ($balance === 'clear') {
            $where[] = 's.current_balance <= 0';
        }

        $sql = "SELECT s.*,
                       COUNT(p.id)              AS total_purchases,
                       COALESCE(SUM(p.total),0) AS total_purchased,
                       MAX(p.purchase_date)     AS last_purchase
                FROM suppliers s
                LEFT JOIN purchases p ON p.supplier_id = s.id AND p.status = 'received'
                WHERE " . implode(' AND ', $where) . "
                GROUP BY s.id
                ORDER BY s.supplier_name ASC";

        $pagination = Database::paginate($sql, $params, max(1, (int)$this->get('page', 1)));

        // Summary stats
        $totalSuppliers   = (int)   Database::fetchColumn("SELECT COUNT(*) FROM suppliers WHERE status='active'");
        $totalBalance     = (float) Database::fetchColumn("SELECT COALESCE(SUM(current_balance),0) FROM suppliers WHERE status='active'");
        $suppliersWithDue = (int)   Database::fetchColumn("SELECT COUNT(*) FROM suppliers WHERE status='active' AND current_balance > 0");

        $pageTitle  = 'Suppliers';
        $breadcrumb = [['label' => 'Suppliers']];
        ob_start();
        require APP_PATH . '/views/suppliers/index.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }
    public function create(): void
    {
        Auth::requirePermission('suppliers.create');
        $pageTitle='Add Supplier'; $breadcrumb=[['label'=>'Suppliers','url'=>APP_URL.'/suppliers'],['label'=>'Add']];
        ob_start(); require APP_PATH.'/views/suppliers/form.php'; $content=ob_get_clean();
        require APP_PATH.'/views/layouts/main.php';
    }
    public function store(): void
    {
        Auth::requirePermission('suppliers.create'); Auth::requireCsrf();
        $d = $this->supplierData();
        Database::insert('INSERT INTO suppliers (supplier_name,contact_person,phone,email,address,opening_balance,current_balance,status) VALUES (?,?,?,?,?,?,?,?)',
            [$d['name'],$d['contact'],$d['phone'],$d['email'],$d['address'],$d['opening'],$d['opening'],'active']);
        redirectWith(APP_URL.'/suppliers','success','Supplier added.');
    }
    public function edit(string $id): void
    {
        Auth::requirePermission('suppliers.edit');
        $supplier = Database::fetchOne('SELECT * FROM suppliers WHERE id=?',[(int)$id]);
        if (!$supplier) { http_response_code(404); die('Not found.'); }
        $pageTitle='Edit Supplier'; $breadcrumb=[['label'=>'Suppliers','url'=>APP_URL.'/suppliers'],['label'=>'Edit']];
        ob_start(); require APP_PATH.'/views/suppliers/form.php'; $content=ob_get_clean();
        require APP_PATH.'/views/layouts/main.php';
    }
    public function update(string $id): void
    {
        Auth::requirePermission('suppliers.edit'); Auth::requireCsrf();
        $d = $this->supplierData();
        Database::execute('UPDATE suppliers SET supplier_name=?,contact_person=?,phone=?,email=?,address=?,status=? WHERE id=?',
            [$d['name'],$d['contact'],$d['phone'],$d['email'],$d['address'],$d['status'],(int)$id]);
        redirectWith(APP_URL.'/suppliers','success','Supplier updated.');
    }
    public function show(string $id): void
    {
        Auth::requirePermission('suppliers.view');

        $supplier = Database::fetchOne('SELECT * FROM suppliers WHERE id = ?', [(int)$id]);
        if (!$supplier) {
            http_response_code(404);
            require APP_PATH . '/views/errors/404.php';
            return;
        }

        // Purchase history (recent 50)
        $purchases = Database::fetchAll(
            "SELECT * FROM purchases
             WHERE supplier_id = ?
             ORDER BY purchase_date DESC
             LIMIT 50",
            [(int)$id]
        );

        // Payment history
        $payments = Database::fetchAll(
            "SELECT sp.*, p.invoice_no, u.name AS paid_by
             FROM supplier_payments sp
             JOIN purchases p ON p.id = sp.purchase_id
             LEFT JOIN users u ON u.id = sp.created_by
             WHERE sp.supplier_id = ?
             ORDER BY sp.payment_date DESC, sp.id DESC
             LIMIT 30",
            [(int)$id]
        );

        // Pending cheques
        $pendingCheques = Database::fetchAll(
            "SELECT ct.*, p.invoice_no
             FROM cheque_tracking ct
             JOIN purchases p ON p.id = ct.purchase_id
             WHERE ct.purchase_id IN (SELECT id FROM purchases WHERE supplier_id = ?)
               AND ct.status = 'pending'
               AND ct.transaction_type = 'purchase'
             ORDER BY ct.cheque_date ASC",
            [(int)$id]
        );

        // Stats
        $stats = Database::fetchOne(
            "SELECT COUNT(*)                          AS total_invoices,
                    COALESCE(SUM(total),0)            AS total_purchased,
                    COALESCE(SUM(paid),0)             AS total_paid,
                    COALESCE(SUM(balance),0)          AS total_balance,
                    COUNT(CASE WHEN balance > 0 THEN 1 END) AS due_invoices
             FROM purchases WHERE supplier_id = ? AND status = 'received'",
            [(int)$id]
        );

        $pageTitle  = $supplier['supplier_name'];
        $breadcrumb = [
            ['label' => 'Suppliers', 'url' => APP_URL . '/suppliers'],
            ['label' => $supplier['supplier_name']],
        ];
        ob_start();
        require APP_PATH . '/views/suppliers/view.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }
    // ── Delete a supplier ──────────────────────────────────────
    public function delete(string $id): void
    {
        Auth::requirePermission('suppliers.delete');
        Auth::requireCsrf();

        $supId = (int) $id;

        $sup = Database::fetchOne('SELECT * FROM suppliers WHERE id = ?', [$supId]);
        if (!$sup) {
            redirectWith(APP_URL.'/suppliers', 'error', 'Supplier not found.');
            return;
        }

        // Check for related history that would block a hard delete
        $purchaseCount = (int) Database::fetchColumn(
            'SELECT COUNT(*) FROM purchases WHERE supplier_id = ?', [$supId]
        );
        $paymentCount = (int) Database::fetchColumn(
            'SELECT COUNT(*) FROM supplier_payments WHERE supplier_id = ?', [$supId]
        );

        if ($purchaseCount > 0 || $paymentCount > 0) {
            // Has history — cannot hard delete safely. Deactivate instead.
            Database::execute(
                "UPDATE suppliers SET status = 'inactive' WHERE id = ?", [$supId]
            );
            Auth::logAudit(Auth::id(), 'supplier_deactivate', 'suppliers',
                "Supplier \"{$sup['supplier_name']}\" deactivated (has {$purchaseCount} purchases, ".
                "{$paymentCount} payments) — could not hard delete.");
            redirectWith(APP_URL.'/suppliers', 'success',
                "\"{$sup['supplier_name']}\" has {$purchaseCount} purchase order(s) on record, so it ".
                'was deactivated instead of deleted (history is preserved).');
            return;
        }

        // No history — safe to permanently delete
        try {
            Database::execute('DELETE FROM suppliers WHERE id = ?', [$supId]);
            Auth::logAudit(Auth::id(), 'supplier_delete', 'suppliers',
                "Supplier \"{$sup['supplier_name']}\" permanently deleted.");
            redirectWith(APP_URL.'/suppliers', 'success',
                "\"{$sup['supplier_name']}\" deleted permanently.");
        } catch (\Exception $e) {
            redirectWith(APP_URL.'/suppliers', 'error',
                'Delete failed: ' . $e->getMessage());
        }
    }

    private function supplierData(): array
    {
        return [
            'name'    => trim($this->post('supplier_name','')),
            'contact' => trim($this->post('contact_person','')),
            'phone'   => trim($this->post('phone','')),
            'email'   => trim($this->post('email','')),
            'address' => trim($this->post('address','')),
            'opening' => (float)$this->post('opening_balance',0),
            'status'  => $this->post('status','active'),
        ];
    }
}