<?php

class RiderController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('delivery', 'view');

        $userModel = new User();
        $allRiders = $userModel->ridersWithStats();

        $search = trim($this->input('search', ''));
        $riders = $allRiders;
        if ($search !== '') {
            $needle = mb_strtolower($search);
            $riders = array_values(array_filter($allRiders, function ($r) use ($needle) {
                return str_contains(mb_strtolower($r['full_name']), $needle)
                    || str_contains(mb_strtolower($r['phone'] ?? ''), $needle)
                    || str_contains(mb_strtolower($r['vehicle_number'] ?? ''), $needle);
            }));
        }

        $deliveryModel = new Delivery();
        $historyByRider = [];
        foreach ($riders as $r) {
            $historyByRider[$r['id']] = $deliveryModel->historyForRider((int) $r['id']);
        }

        $this->view('riders.index', [
            'pageTitle'      => 'Delivery Riders',
            'riders'         => $riders,
            'historyByRider' => $historyByRider,
            'summary'        => $userModel->riderStatsSummary(),
            'search'         => $search,
            'csrf'           => $this->csrfField(),
        ]);
    }

    public function store(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $fullName = trim($this->input('full_name', ''));
        $phone    = trim($this->input('phone', ''));
        $username = trim($this->input('username', ''));
        $password = $this->input('password', '');
        $vehicleType = $this->input('vehicle_type', '') ?: null;
        $vehicleNumber = trim($this->input('vehicle_number', '')) ?: null;

        if ($fullName === '' || $username === '' || $password === '') {
            $this->redirect('riders');
            return;
        }

        $userModel = new User();
        if ($userModel->usernameExists($username)) {
            $this->redirect('riders');
            return;
        }

        $db = Database::getConnection();
        $riderRole = $db->query("SELECT id FROM roles WHERE role_name = 'RIDER' LIMIT 1")->fetch();
        if (!$riderRole) {
            $this->redirect('riders');
            return;
        }

        $photoPath = $this->handlePhotoUpload();

        $userModel->insert([
            'full_name'      => $fullName,
            'username'       => $username,
            'phone'          => $phone ?: null,
            'password_hash'  => password_hash($password, PASSWORD_DEFAULT),
            'role_id'        => $riderRole['id'],
            'wage_type'      => 'DAILY',
            'vehicle_type'   => $vehicleType,
            'vehicle_number' => $vehicleNumber,
            'photo_path'     => $photoPath,
            'is_active'      => 1,
        ]);

        AuditLogger::log(Auth::id(), 'RIDER_CREATE', 'delivery', "Added delivery rider: {$fullName}");
        $this->redirect('riders');
    }

    public function update(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $userModel = new User();
        $rider = $userModel->find($id);
        if (!$rider) {
            $this->redirect('riders');
            return;
        }

        $photoPath = $rider['photo_path'];
        if ((int) $this->input('remove_photo', 0) === 1 && $photoPath) {
            $this->deleteUploadedPhoto($photoPath);
            $photoPath = null;
        }
        $newPhoto = $this->handlePhotoUpload();
        if ($newPhoto) {
            if ($photoPath) {
                $this->deleteUploadedPhoto($photoPath);
            }
            $photoPath = $newPhoto;
        }

        $data = [
            'full_name'      => trim($this->input('full_name', $rider['full_name'])),
            'phone'          => trim($this->input('phone', '')) ?: null,
            'vehicle_type'   => $this->input('vehicle_type', '') ?: null,
            'vehicle_number' => trim($this->input('vehicle_number', '')) ?: null,
            'photo_path'     => $photoPath,
        ];

        $newUsername = trim($this->input('username', ''));
        if ($newUsername !== '' && $newUsername !== $rider['username']) {
            if ($userModel->usernameExists($newUsername, $id)) {
                AuditLogger::log(Auth::id(), 'RIDER_UPDATE_FAILED', 'delivery', "Username '{$newUsername}' already taken — update rejected for rider #{$id}");
                $this->redirect('riders');
                return;
            }
            $data['username'] = $newUsername;
        }

        $newPassword = $this->input('password', '');
        if ($newPassword !== '') {
            $data['password_hash'] = password_hash($newPassword, PASSWORD_DEFAULT);
        }

        $userModel->update($id, $data);
        AuditLogger::log(Auth::id(), 'RIDER_UPDATE', 'delivery', "Updated rider #{$id}");
        $this->redirect('riders');
    }

    public function toggleActive(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $userModel = new User();
        $rider = $userModel->find($id);

        if ($rider && !$rider['is_protected']) {
            $userModel->update($id, ['is_active' => $rider['is_active'] ? 0 : 1]);
            AuditLogger::log(Auth::id(), 'RIDER_TOGGLE', 'delivery', "Rider #{$id} active -> " . ($rider['is_active'] ? '0' : '1'));
        }

        $this->redirect('riders');
    }

    // --- Photo upload helpers ---

    private function handlePhotoUpload(): ?string
    {
        if (empty($_FILES['photo']) || $_FILES['photo']['error'] === UPLOAD_ERR_NO_FILE) {
            return null;
        }
        if ($_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
            return null;
        }

        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $mime = mime_content_type($_FILES['photo']['tmp_name']);
        if (!isset($allowed[$mime])) {
            return null; // silently ignore unsupported file types
        }
        if ($_FILES['photo']['size'] > 3 * 1024 * 1024) {
            return null; // 3MB limit
        }

        $ext = $allowed[$mime];
        $filename = 'rider_' . bin2hex(random_bytes(8)) . '.' . $ext;
        $uploadDir = ROOT_PATH . '/public/uploads/riders/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        if (!move_uploaded_file($_FILES['photo']['tmp_name'], $uploadDir . $filename)) {
            return null;
        }

        return 'uploads/riders/' . $filename;
    }

    private function deleteUploadedPhoto(?string $relativePath): void
    {
        if (!$relativePath) {
            return;
        }
        $fullPath = ROOT_PATH . '/public/' . $relativePath;
        if (is_file($fullPath)) {
            @unlink($fullPath);
        }
    }
}
