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

    public function index() {
        $search = $_GET['search'] ?? ''; $status = $_GET['status'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE wo.deleted_at IS NULL AND wo.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (wo.title LIKE ? OR v.company_name LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s]); }
        if ($status) { $where .= " AND wo.status = ?"; $params[] = $status; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM work_orders wo LEFT JOIN vendors v ON wo.vendor_id=v.id $where", $params);
        $offset = ($page - 1) * $perPage;
        $orders = $this->db->fetchAll("SELECT wo.*, v.company_name as vendor_name, p.name as property_name, u.unit_number FROM work_orders wo LEFT JOIN vendors v ON wo.vendor_id=v.id LEFT JOIN properties p ON wo.property_id=p.id LEFT JOIN units u ON wo.unit_id=u.id $where ORDER BY wo.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $pagination = paginationHtml($total, $page, $perPage, '?page=workorders');
        require 'app/views/workorders/index.php';
    }

    public function create() {
        $order = null; $cid = Auth::user()['company_id'];
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $maintenanceRequests = $this->db->fetchAll("SELECT id, title FROM maintenance_requests WHERE company_id=? AND deleted_at IS NULL AND status NOT IN ('completed','closed','cancelled') ORDER BY created_at DESC", [$cid]);
        require 'app/views/workorders/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('title');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=workorders&action=create'); }
        $this->db->insert('work_orders', [
            'company_id' => Auth::user()['company_id'], 'maintenance_request_id' => $_POST['maintenance_request_id'] ?: null,
            'property_id' => $_POST['property_id'] ?: null, 'unit_id' => $_POST['unit_id'] ?: null,
            'vendor_id' => $_POST['vendor_id'] ?: null, 'title' => $_POST['title'],
            'description' => $_POST['description'] ?? null, 'priority' => $_POST['priority'] ?? 'medium',
            'status' => $_POST['status'] ?? 'new', 'scheduled_date' => $_POST['scheduled_date'] ?: null,
            'completed_date' => $_POST['completed_date'] ?: null, 'cost' => $_POST['cost'] ?: null,
        ]);
        flash('success', 'Work order created.'); redirect('?page=workorders');
    }

    public function show($id) {
        $cid = Auth::user()['company_id'];
        $order = $this->db->fetch("SELECT wo.*, v.company_name as vendor_name, v.phone as vendor_phone, v.email as vendor_email, p.name as property_name, u.unit_number, mr.title as request_title FROM work_orders wo LEFT JOIN vendors v ON wo.vendor_id=v.id LEFT JOIN properties p ON wo.property_id=p.id LEFT JOIN units u ON wo.unit_id=u.id LEFT JOIN maintenance_requests mr ON wo.maintenance_request_id=mr.id WHERE wo.id=? AND wo.company_id=? AND wo.deleted_at IS NULL", [$id, $cid]);
        if (!$order) { flash('error', 'Work order not found.'); redirect('?page=workorders'); }
        require 'app/views/workorders/show.php';
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $order = $this->db->fetch("SELECT * FROM work_orders WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$order) { flash('error', 'Work order not found.'); redirect('?page=workorders'); }
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $maintenanceRequests = $this->db->fetchAll("SELECT id, title FROM maintenance_requests WHERE company_id=? AND deleted_at IS NULL ORDER BY created_at DESC", [$cid]);
        require 'app/views/workorders/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('work_orders', [
            'maintenance_request_id' => $_POST['maintenance_request_id'] ?: null, 'property_id' => $_POST['property_id'] ?: null,
            'unit_id' => $_POST['unit_id'] ?: null, 'vendor_id' => $_POST['vendor_id'] ?: null,
            'title' => $_POST['title'], 'description' => $_POST['description'] ?? null,
            'priority' => $_POST['priority'] ?? 'medium', 'status' => $_POST['status'] ?? 'new',
            'scheduled_date' => $_POST['scheduled_date'] ?: null, 'completed_date' => $_POST['completed_date'] ?: null,
            'cost' => $_POST['cost'] ?: null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Work order updated.'); redirect('?page=workorders');
    }

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