<?php

namespace App\Repositories;

use App\Config\Database;

class AuthRepository
{
    /**
     * Find user by username and license key
     * 
     * @throws Exception
     *  
     * @return array
     * 
     * @param string $username
     * @param string $licenseKey
     */
    public function findUserWithLicense(string $username, string $licenseKey): ?array
    {
        $conn = Database::connection();

        $sql = "
            SELECT 
                c.id AS client_id,
                c.username,
                c.password_hash,
                c.is_active AS client_active,
                c.locked_until,
                c.failed_attempts,

                l.id AS license_id,
                l.license_key,
                l.is_active AS license_active,
                l.expires_at,
                l.last_revoked_at,

                co.id AS company_id,
                co.name_company,
                co.is_active AS company_active

            FROM clients c

            INNER JOIN license_clients lc
                ON lc.client_id = c.id

            INNER JOIN licenses l
                ON l.id = lc.license_id

            INNER JOIN license_companies lcm
                ON lcm.license_id = l.id

            INNER JOIN companies co
                ON co.id = lcm.company_id

            WHERE 
                c.username = ?
                AND l.license_key = ?

            LIMIT 1;
        ";

        $stmt = $conn->prepare($sql);

        if ($stmt === false) {
            throw new \Exception(
                'SQL Prepare Error: ' . $conn->error
            );
        }

        $stmt->bind_param("ss", $username, $licenseKey);

        if (!$stmt) {
            throw new \Exception($conn->error);
        }
        $stmt->execute();

        $result = $stmt->get_result();
        return $result->fetch_assoc() ?: null;
    }

    /**
     * Increment failed attempts and set lock time
     * 
     * @throws Exception
     * 
     * @param int $clientId
     * 
     * @return void
     */
    public function incrementFailedAttempts(int $clientId): void
    {
        $conn = Database::connection();

        $sql = "
        UPDATE clients
        SET 
            failed_attempts = failed_attempts + 1,
            locked_until = IF(
                failed_attempts + 1 >= 5,
                DATE_ADD(NOW(), INTERVAL 15 MINUTE),
                locked_until
            )
        WHERE id = ?
    ";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $clientId);
        $stmt->execute();
    }

    public function resetFailedAttempts(int $clientId): void
    {
        $conn = Database::connection();

        $sql = "
        UPDATE clients
        SET failed_attempts = 0, locked_until = NULL
        WHERE id = ?
    ";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $clientId);
        $stmt->execute();
    }
}
