<?php
class VendorController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? ''; $category = $_GET['category'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE v.deleted_at IS NULL AND v.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (v.company_name LIKE ? OR v.contact_name LIKE ? OR v.email LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
        if ($category) { $where .= " AND v.service_category = ?"; $params[] = $category; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM vendors v $where", $params);
        $offset = ($page - 1) * $perPage;
        $vendors = $this->db->fetchAll("SELECT v.*, (SELECT COUNT(*) FROM work_orders wo WHERE wo.vendor_id=v.id AND wo.deleted_at IS NULL) as wo_count FROM vendors v $where ORDER BY v.company_name ASC LIMIT $perPage OFFSET $offset", $params);
        $pagination = paginationHtml($total, $page, $perPage, '?page=vendors');
        require 'app/views/vendors/index.php';
    }

    public function create() { $vendor = null; require 'app/views/vendors/form.php'; }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('company_name')->required('email')->email('email');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=vendors&action=create'); }
        $this->db->insert('vendors', [
            'company_id' => Auth::user()['company_id'], 'company_name' => $_POST['company_name'],
            'contact_name' => $_POST['contact_name'] ?? null, 'email' => $_POST['email'],
            'phone' => $_POST['phone'] ?? null, 'service_category' => $_POST['service_category'] ?? null,
            'address' => $_POST['address'] ?? null, 'city' => $_POST['city'] ?? null,
            'state' => $_POST['state'] ?? null, 'zip' => $_POST['zip'] ?? null,
            'insurance_expiry' => $_POST['insurance_expiry'] ?: null, 'w9_status' => $_POST['w9_status'] ?? 'pending',
            'rating' => $_POST['rating'] ?: null, 'notes' => $_POST['notes'] ?? null,
        ]);
        flash('success', 'Vendor created.'); redirect('?page=vendors');
    }

    public function show($id) {
        $cid = Auth::user()['company_id'];
        $vendor = $this->db->fetch("SELECT * FROM vendors WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$vendor) { flash('error', 'Vendor not found.'); redirect('?page=vendors'); }
        $workOrders = $this->db->fetchAll("SELECT wo.*, p.name as property_name FROM work_orders wo LEFT JOIN properties p ON wo.property_id=p.id WHERE wo.vendor_id=? AND wo.deleted_at IS NULL ORDER BY wo.created_at DESC LIMIT 10", [$id]);
        require 'app/views/vendors/show.php';
    }

    public function edit($id) {
        $vendor = $this->db->fetch("SELECT * FROM vendors WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$vendor) { flash('error', 'Vendor not found.'); redirect('?page=vendors'); }
        require 'app/views/vendors/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('vendors', [
            'company_name' => $_POST['company_name'], 'contact_name' => $_POST['contact_name'] ?? null,
            'email' => $_POST['email'], 'phone' => $_POST['phone'] ?? null,
            'service_category' => $_POST['service_category'] ?? null, 'address' => $_POST['address'] ?? null,
            'city' => $_POST['city'] ?? null, 'state' => $_POST['state'] ?? null, 'zip' => $_POST['zip'] ?? null,
            'insurance_expiry' => $_POST['insurance_expiry'] ?: null, 'w9_status' => $_POST['w9_status'] ?? 'pending',
            'rating' => $_POST['rating'] ?: null, 'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Vendor updated.'); redirect('?page=vendors');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->softDelete('vendors', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Vendor deleted.'); redirect('?page=vendors');
    }
}
