<?php

class User extends BaseModel
{
    public const ROLES=['owner','admin','dispatcher','accountant','driver','carrier','team','maintenance'];

    public function all(?string $search=null): array
    {
        $sql='SELECT users.*,drivers.name driver_name,carriers.company_name carrier_name FROM users LEFT JOIN drivers ON drivers.id=users.driver_id LEFT JOIN carriers ON carriers.id=users.carrier_id';
        $params=[];
        if($search){$sql.=' WHERE users.name LIKE ? OR users.email LIKE ? OR users.role LIKE ? OR drivers.name LIKE ? OR carriers.company_name LIKE ?';$term="%{$search}%";$params=[$term,$term,$term,$term,$term];}
        $sql.=' ORDER BY users.id DESC';$stmt=$this->db->prepare($sql);$stmt->execute($params);return $stmt->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt=$this->db->prepare('SELECT * FROM users WHERE id=?');$stmt->execute([$id]);return $stmt->fetch()?:null;
    }

    public function create(array $data): void
    {
        [$role,$driverId,$carrierId,$status,$permissions]=$this->normalizedAccess($data);
        $stmt=$this->db->prepare('INSERT INTO users (name,email,password,role,status,driver_id,carrier_id,department,phone,permissions) VALUES (?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([
            trim((string)$data['name']),trim((string)$data['email']),password_hash((string)$data['password'],PASSWORD_DEFAULT),$role,$status,$driverId,$carrierId,
            trim((string)($data['department']??''))?:null,trim((string)($data['phone']??''))?:null,$permissions,
        ]);
    }

    public function update(int $id,array $data): void
    {
        [$role,$driverId,$carrierId,$status,$permissions]=$this->normalizedAccess($data);
        $fields='name=?,email=?,role=?,status=?,driver_id=?,carrier_id=?,department=?,phone=?,permissions=?';
        $params=[trim((string)$data['name']),trim((string)$data['email']),$role,$status,$driverId,$carrierId,trim((string)($data['department']??''))?:null,trim((string)($data['phone']??''))?:null,$permissions];
        if(!empty($data['password'])){$fields.=',password=?';$params[]=password_hash((string)$data['password'],PASSWORD_DEFAULT);}
        $params[]=$id;$this->db->prepare("UPDATE users SET {$fields} WHERE id=?")->execute($params);
    }

    public function delete(int $id): void
    {
        if($id===(int)($_SESSION['user_id']??0))return;$this->db->prepare('DELETE FROM users WHERE id=?')->execute([$id]);
    }

    private function normalizedAccess(array $data): array
    {
        $role=in_array(($data['role']??'dispatcher'),self::ROLES,true)?$data['role']:'dispatcher';
        $driverId=$role==='driver'&&!empty($data['driver_id'])?(int)$data['driver_id']:null;
        $carrierId=$role==='carrier'&&!empty($data['carrier_id'])?(int)$data['carrier_id']:null;
        $status=in_array(($data['status']??'active'),['active','inactive'],true)?$data['status']:'active';
        $permissions=!empty($data['permissions'])?json_encode(array_values(array_unique((array)$data['permissions']))):null;
        return [$role,$driverId,$carrierId,$status,$permissions];
    }
}
