<?php
// app/Models/User.php
class User {
    public static function find(int $id): ?array {
        $s = db()->prepare('SELECT id,name,email,role,phone,created_at FROM users WHERE id=?');
        $s->execute([$id]);
        return $s->fetch() ?: null;
    }
    public static function findByEmail(string $email): ?array {
        $s = db()->prepare('SELECT * FROM users WHERE email=?');
        $s->execute([$email]);
        return $s->fetch() ?: null;
    }
    public static function create(array $d): int {
        $s = db()->prepare('INSERT INTO users(name,email,password,role,phone) VALUES(?,?,?,?,?)');
        $s->execute([$d['name'],$d['email'],password_hash($d['password'],PASSWORD_BCRYPT),$d['role'],$d['phone']??null]);
        return (int)db()->lastInsertId();
    }
    public static function update(int $id, array $d): void {
        $sets=[]; $vals=[];
        foreach(['name','phone'] as $f) { if(isset($d[$f])){ $sets[]="$f=?"; $vals[]=$d[$f]; } }
        if(isset($d['password'])){ $sets[]='password=?'; $vals[]=password_hash($d['password'],PASSWORD_BCRYPT); }
        if(!$sets) return;
        $vals[]=$id;
        db()->prepare('UPDATE users SET '.implode(',',$sets).' WHERE id=?')->execute($vals);
    }
    public static function allDrivers(): array {
        $s = db()->prepare("SELECT id,name,email,phone FROM users WHERE role='driver' ORDER BY name");
        $s->execute(); return $s->fetchAll();
    }

    // ── دوال إدارية (Admin) ───────────────────────────────────

    /** كل المستخدمين مع بحث/تصفية بالدور */
    public static function all(string $search = '', string $role = ''): array {
        $sql = "SELECT id,name,email,role,phone,created_at FROM users WHERE 1=1";
        $p = [];
        if ($search !== '') {
            $sql .= " AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)";
            $like = '%'.$search.'%';
            $p[] = $like; $p[] = $like; $p[] = $like;
        }
        if (in_array($role, ['owner','driver','officer','admin'], true)) {
            $sql .= " AND role=?"; $p[] = $role;
        }
        $sql .= " ORDER BY created_at DESC";
        $s = db()->prepare($sql); $s->execute($p);
        return $s->fetchAll();
    }

    /** إنشاء مستخدم بأي دور (يستخدمه المدير) */
    public static function adminCreate(array $d): int {
        $role = in_array($d['role'] ?? '', ['owner','driver','officer','admin'], true) ? $d['role'] : 'driver';
        $s = db()->prepare('INSERT INTO users(name,email,password,role,phone) VALUES(?,?,?,?,?)');
        $s->execute([
            $d['name'], $d['email'],
            password_hash($d['password'], PASSWORD_BCRYPT),
            $role, $d['phone'] ?? null,
        ]);
        return (int)db()->lastInsertId();
    }

    public static function updateRole(int $id, string $role): void {
        if (!in_array($role, ['owner','driver','officer','admin'], true)) return;
        db()->prepare('UPDATE users SET role=? WHERE id=?')->execute([$role, $id]);
    }

    public static function resetPassword(int $id, string $newPassword): void {
        db()->prepare('UPDATE users SET password=? WHERE id=?')
            ->execute([password_hash($newPassword, PASSWORD_BCRYPT), $id]);
    }

    public static function deleteById(int $id): void {
        db()->prepare('DELETE FROM users WHERE id=?')->execute([$id]);
    }

    public static function countAdmins(): int {
        return (int)db()->query("SELECT COUNT(*) FROM users WHERE role='admin'")->fetchColumn();
    }
}
