<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Client;
use App\Services\EmailService;

class ClientAuthController extends Controller
{
    public function loginForm()
    {
        if (isset($_SESSION['client_id'])) {
            $this->redirect('/client/dashboard');
        }
        $this->render('client/login', ['pageTitle' => 'Client Login']);
    }

    public function login()
    {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        $clientModel = new Client();
        $client = $clientModel->findByUsername($username);

        if (!$client) {
            $_SESSION['error'] = 'Invalid username or client code.';
            $this->redirect('/client/login');
            return;
        }

        $clientStatus = $client['status'] ?? 'active';
        if ($clientStatus !== 'active') {
            $_SESSION['error'] = 'Account is inactive. Contact support.';
            $this->redirect('/client/login');
            return;
        }

        if (!$clientModel->verifyPassword($client, $password)) {
            $_SESSION['error'] = 'Invalid password.';
            $this->redirect('/client/login');
            return;
        }

        $_SESSION['client_id'] = $client['id'];
        $_SESSION['client_name'] = $client['full_name'];
        $_SESSION['client_code'] = $client['client_code'];
        $clientModel->updateLastLogin($client['id']);
        $this->redirect('/client/dashboard');
    }

    public function logout()
    {
        unset($_SESSION['client_id'], $_SESSION['client_name'], $_SESSION['client_code']);
        session_destroy();
        $this->redirect('/client/login');
    }

    // --- Password Reset ---

    public function forgotPasswordForm()
    {
        $this->render('client/forgot_password', ['pageTitle' => 'Forgot Password']);
    }

    public function sendResetLink()
    {
        $email = trim($_POST['email'] ?? '');
        if (empty($email)) {
            $_SESSION['error'] = 'Please enter your email address.';
            $this->redirect('/client/forgot-password');
            return;
        }

        $clientModel = new Client();
        $client = $clientModel->findByEmail($email);

        if (!$client) {
            $_SESSION['error'] = 'No account found with that email address.';
            $this->redirect('/client/forgot-password');
            return;
        }

        // Generate token and expiry (1 hour)
        $token = bin2hex(random_bytes(32));
        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $clientModel->setResetToken($client['id'], $token, $expiry);

        // Build reset URL
        $resetUrl = $this->baseUrl('/client/reset-password?token=' . $token);

        // Send email
        try {
            $emailService = new EmailService();
            $subject = "Password Reset - Finance Manager";
            $body = "
                <h3>Dear {$client['full_name']},</h3>
                <p>We received a request to reset your password.</p>
                <p>Click the link below to set a new password (valid for 1 hour):</p>
                <p><a href='{$resetUrl}'>{$resetUrl}</a></p>
                <p>If you did not request this, ignore this email.</p>
            ";
            $emailService->send($email, $subject, $body);
            $_SESSION['success'] = 'A reset link has been sent to your email address.';
        } catch (\Exception $e) {
            $_SESSION['error'] = 'Could not send email. Please try again later.';
        }
        $this->redirect('/client/login');
    }

    public function resetPasswordForm()
    {
        $token = $_GET['token'] ?? '';
        if (empty($token)) {
            $this->redirect('/client/login');
        }

        $clientModel = new Client();
        $client = $clientModel->findByResetToken($token);
        if (!$client) {
            $_SESSION['error'] = 'Invalid or expired reset token.';
            $this->redirect('/client/login');
            return;
        }

        $this->render('client/reset_password', [
            'token' => $token,
            'pageTitle' => 'Set New Password'
        ]);
    }

    public function updatePassword()
    {
        $token = $_POST['token'] ?? '';
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';

        if ($password !== $confirm) {
            $_SESSION['error'] = 'Passwords do not match.';
            $this->redirect('/client/reset-password?token=' . urlencode($token));
            return;
        }

        $clientModel = new Client();
        $client = $clientModel->findByResetToken($token);
        if (!$client) {
            $_SESSION['error'] = 'Invalid or expired token.';
            $this->redirect('/client/login');
            return;
        }

        $clientModel->updatePassword($client['id'], $password);
        $_SESSION['success'] = 'Password has been reset. You can now log in.';
        $this->redirect('/client/login');
    }
}