<?php

class Maintenance extends BaseModel
{
    public function all(?string $search = null): array
    {
        $sql = 'SELECT maintenance_records.*, trucks.unit_number AS truck_number, trailers.trailer_number
                FROM maintenance_records
                LEFT JOIN trucks ON trucks.id = maintenance_records.truck_id
                LEFT JOIN trailers ON trailers.id = maintenance_records.trailer_id';
        $params = [];
        if ($search) {
            $sql .= ' WHERE maintenance_records.service_type LIKE ? OR trucks.unit_number LIKE ? OR trailers.trailer_number LIKE ?';
            $term = "%{$search}%";
            $params = [$term, $term, $term];
        }
        $sql .= ' ORDER BY maintenance_records.service_date DESC, maintenance_records.id DESC';
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    public function create(array $data): void
    {
        $stmt = $this->db->prepare('INSERT INTO maintenance_records (truck_id, trailer_id, service_type, service_date, next_service_date, mileage, cost, status, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $data['truck_id'] ?: null, $data['trailer_id'] ?: null, $data['service_type'], $data['service_date'], $data['next_service_date'] ?: null,
            $data['mileage'] ?: null, $data['cost'] ?: 0, $data['status'] ?: 'completed', $data['notes'] ?: null,
        ]);
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM maintenance_records WHERE id = ?');
        $stmt->execute([$id]);
    }

    public function dueSoon(int $days = 30): array
    {
        $stmt = $this->db->prepare("SELECT maintenance_records.*, trucks.unit_number AS truck_number, trailers.trailer_number
                                    FROM maintenance_records
                                    LEFT JOIN trucks ON trucks.id = maintenance_records.truck_id
                                    LEFT JOIN trailers ON trailers.id = maintenance_records.trailer_id
                                    WHERE next_service_date IS NOT NULL AND next_service_date <= DATE_ADD(CURDATE(), INTERVAL ? DAY)
                                    ORDER BY next_service_date ASC LIMIT 12");
        $stmt->execute([$days]);
        return $stmt->fetchAll();
    }
}
