<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Auth;
use App\Csrf;
use App\Pin;
use App\Repositories\Container;

class HubAccountController
{
    public function show(): void
    {
        $user = Auth::user();
        $artistProfile = null;
        $weekly = [];
        if (!empty($user['artist_profile_id'])) {
            $artistProfile = Container::artists()->find($user['artist_profile_id']);
            $weekly = Container::schedules()->weeklyForArtist($user['artist_profile_id']);
        }
        render('hub', 'hub.account', compact('user', 'artistProfile', 'weekly'), t('hub.account.title'));
    }

    public function schedule(): void
    {
        $user = Auth::user();
        if (empty($user['artist_profile_id'])) { redirect('/hub/account'); }
        $artistProfile = Container::artists()->find($user['artist_profile_id']);
        $weekly = Container::schedules()->weeklyForArtist($user['artist_profile_id']);
        render('hub', 'hub.account', compact('user', 'artistProfile', 'weekly'), t('hub.account.title'));
    }

    public function saveSchedule(): void
    {
        Csrf::requireValid();
        $user = Auth::user();
        if (empty($user['artist_profile_id'])) { redirect('/hub/account'); }

        $days  = $_POST['days']  ?? [];
        $start = $_POST['start'] ?? [];
        $end   = $_POST['end']   ?? [];

        $rows = [];
        foreach ($days as $idx => $weekday) {
            $weekday = (int)$weekday;
            $s = trim((string)($start[$idx] ?? ''));
            $e = trim((string)($end[$idx]   ?? ''));
            if ($s && $e && $weekday >= 0 && $weekday <= 6) {
                $rows[] = [
                    'weekday'    => $weekday,
                    'start_time' => $s,
                    'end_time'   => $e,
                ];
            }
        }
        Container::schedules()->replaceWeekly($user['artist_profile_id'], $rows);
        Container::audit()->log($user['id'], 'UPDATE_SCHEDULE', 'artist', $user['artist_profile_id']);
        $_SESSION['_flash']['success'] = t('hub.account.schedule_saved');
        redirect('/hub/account');
    }

    public function changePassword(): void
    {
        Csrf::requireValid();
        $user = Auth::user();
        if (!$user) { redirect('/hub/login'); }

        $old     = (string)($_POST['current_password'] ?? '');
        $new     = (string)($_POST['new_password'] ?? '');
        $confirm = (string)($_POST['confirm_password'] ?? '');

        if (empty($user['password_hash']) || !password_verify($old, $user['password_hash'])) {
            $_SESSION['_flash']['error'] = t('hub.account.wrong_current_password');
            redirect('/hub/account');
        }
        if (strlen($new) < 8) {
            $_SESSION['_flash']['error'] = t('hub.account.password_too_short');
            redirect('/hub/account');
        }
        if ($new !== $confirm) {
            $_SESSION['_flash']['error'] = t('hub.account.password_mismatch');
            redirect('/hub/account');
        }
        Container::users()->save(array_merge($user, [
            'password_hash' => password_hash($new, PASSWORD_DEFAULT),
        ]));
        Container::audit()->log($user['id'], 'CHANGE_PASSWORD', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('hub.account.password_changed');
        redirect('/hub/account');
    }

    public function changePin(): void
    {
        Csrf::requireValid();
        $user = Auth::user();
        if (!$user) { redirect('/hub/login'); }

        $old     = (string)($_POST['current_pin'] ?? '');
        $new     = (string)($_POST['new_pin'] ?? '');
        $confirm = (string)($_POST['confirm_pin'] ?? '');

        // Require old PIN unless none set yet
        if (!empty($user['pin_hash'])) {
            if (!Pin::verify($old, $user['pin_hash'])) {
                $_SESSION['_flash']['error'] = t('hub.account.wrong_current_pin');
                redirect('/hub/account');
            }
        }
        if (!preg_match('/^\d{4,6}$/', $new)) {
            $_SESSION['_flash']['error'] = t('hub.account.pin_format');
            redirect('/hub/account');
        }
        if ($new !== $confirm) {
            $_SESSION['_flash']['error'] = t('hub.account.pin_mismatch');
            redirect('/hub/account');
        }
        Container::users()->save(array_merge($user, [
            'pin_hash'   => Pin::hash($new),
            'pin_set_at' => now_iso(),
        ]));
        Container::audit()->log($user['id'], 'CHANGE_PIN', 'user', $user['id']);
        $_SESSION['_flash']['success'] = t('hub.account.pin_changed');
        redirect('/hub/account');
    }
}
