<?php

class CoachController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('coaches/index', [
            'title' => lang('sports.coaches'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.coaches')]],
        ]);
    }

    public function create(Request $request): void
    {
        $this->view('coaches/create', [
            'title' => lang('sports.create_coach'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.coaches'), 'url' => '/sports/coaches'], ['label' => lang('common.create')]],
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'coach_code' => 'required|string|max:20|unique:sport_coaches,coach_code',
            'first_name_en' => 'required|string|max:100',
            'last_name_en' => 'required|string|max:100',
            'first_name_ar' => 'nullable|string|max:100',
            'last_name_ar' => 'nullable|string|max:100',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:191',
            'experience_years' => 'nullable|integer',
            'hourly_rate' => 'nullable|decimal',
            'status' => 'required|in:active,inactive,on_leave,terminated',
            'hire_date' => 'nullable|date',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();

        if ($request->file('photo') && $request->file('photo')['error'] === UPLOAD_ERR_OK) {
            $upload = new FileUpload($request->file('photo'));
            $upload->setAllowedTypes(['jpg','jpeg','png'])->setMaxSize(5*1024*1024)->setDestination('uploads/coaches/');
            if ($upload->validate()) { $data['photo_path'] = $upload->save(); }
        }

        $id = $this->db()->insert('sport_coaches', $data);
        $this->audit('create', 'sport_coach', $id, "Created coach: {$data['first_name_en']} {$data['last_name_en']}");
        $this->json(['success' => true, 'message' => 'Coach created', 'redirect' => '/sports/coaches']);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();
        $coach = $db->fetchOne("SELECT * FROM sport_coaches WHERE id = ?", [$id]);
        if (!$coach) { $this->abort(404); return; }

        $certs = $db->fetchAll("SELECT * FROM sport_coach_certifications WHERE coach_id = ? ORDER BY issue_date DESC", [$id]);
        $classes = $db->fetchAll("SELECT cl.*, sp.name_en as sport_name FROM sport_classes cl LEFT JOIN sports sp ON cl.sport_id = sp.id WHERE cl.coach_id = ? AND cl.is_active = 1 ORDER BY cl.name_en", [$id]);

        $this->view('coaches/show', [
            'title' => $coach['first_name_en'] . ' ' . $coach['last_name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.coaches'), 'url' => '/sports/coaches'], ['label' => $coach['first_name_en']]],
            'coach' => $coach, 'certifications' => $certs, 'classes' => $classes,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $coach = $this->db()->fetchOne("SELECT * FROM sport_coaches WHERE id = ?", [$id]);
        if (!$coach) { $this->abort(404); return; }
        $this->view('coaches/edit', [
            'title' => 'Edit: ' . $coach['first_name_en'] . ' ' . $coach['last_name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.coaches'), 'url' => '/sports/coaches'], ['label' => lang('common.edit')]],
            'coach' => $coach,
        ]);
    }

    public function update(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'first_name_en' => 'required|string|max:100',
            'last_name_en' => 'required|string|max:100',
            'first_name_ar' => 'nullable|string|max:100',
            'last_name_ar' => 'nullable|string|max:100',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:191',
            'experience_years' => 'nullable|integer',
            'hourly_rate' => 'nullable|decimal',
            'status' => 'required|in:active,inactive,on_leave,terminated',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();

        if ($request->file('photo') && $request->file('photo')['error'] === UPLOAD_ERR_OK) {
            $upload = new FileUpload($request->file('photo'));
            $upload->setAllowedTypes(['jpg','jpeg','png'])->setMaxSize(5*1024*1024)->setDestination('uploads/coaches/');
            if ($upload->validate()) { $data['photo_path'] = $upload->save(); }
        }

        $this->db()->update('sport_coaches', $data, 'id = ?', [$id]);
        $this->audit('update', 'sport_coach', $id, "Updated coach: {$data['first_name_en']} {$data['last_name_en']}");
        $this->json(['success' => true, 'message' => 'Coach updated', 'redirect' => '/sports/coaches']);
    }
}