<?php
/**
 * Authentication Class
 * Handles user authentication and sessions
 */

require_once __DIR__ . '/Database.php';

class Auth {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->startSession();
    }

    private function startSession() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    /**
     * Login user
     */
    public function login($email, $password, $isAdmin = false) {
        $table = $isAdmin ? 'admins' : 'users';
        $user = $this->db->fetchOne(
            "SELECT * FROM {$table} WHERE email = ?",
            [$email]
        );

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['is_admin'] = $isAdmin;
            
            if ($isAdmin) {
                $_SESSION['admin_role'] = $user['role'];
            } else {
                $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
            }

            // Update last login
            $this->db->execute(
                "UPDATE {$table} SET last_login = NOW() WHERE id = ?",
                [$user['id']]
            );

            return true;
        }

        return false;
    }

    /**
     * Register new user
     */
    public function register($data) {
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
        
        $sql = "INSERT INTO users (first_name, last_name, email, password, phone, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())";
        
        $params = [
            $data['first_name'],
            $data['last_name'],
            $data['email'],
            $hashedPassword,
            $data['phone'] ?? null
        ];

        try {
            $this->db->execute($sql, $params);
            $userId = $this->db->lastInsertId();
            
            // Auto login after registration
            $user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
            $_SESSION['is_admin'] = false;

            return $userId;
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) { // Duplicate entry
                throw new Exception("Email already exists");
            }
            throw $e;
        }
    }

    /**
     * Logout user
     */
    public function logout() {
        session_destroy();
        $_SESSION = [];
    }

    /**
     * Check if user is logged in
     */
    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }

    /**
     * Check if user is admin
     */
    public function isAdmin() {
        return isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
    }

    /**
     * Get current user ID
     */
    public function getUserId() {
        $userId = $_SESSION['user_id'] ?? null;
        
        // Verify user still exists in database
        if ($userId) {
            $userExists = $this->db->fetchOne("SELECT id FROM users WHERE id = ?", [$userId]);
            if (!$userExists) {
                // User doesn't exist anymore, clear session
                unset($_SESSION['user_id']);
                unset($_SESSION['user_email']);
                unset($_SESSION['user_name']);
                return null;
            }
        }
        
        return $userId;
    }

    /**
     * Get current user data
     */
    public function getUser() {
        if (!$this->isLoggedIn()) {
            return null;
        }

        $isAdmin = $this->isAdmin();
        $table = $isAdmin ? 'admins' : 'users';
        
        return $this->db->fetchOne(
            "SELECT * FROM {$table} WHERE id = ?",
            [$this->getUserId()]
        );
    }

    /**
     * Require login (redirect if not logged in)
     */
    public function requireLogin($redirectTo = '/cont/login') {
        if (!$this->isLoggedIn()) {
            header("Location: {$redirectTo}");
            exit;
        }
    }

    /**
     * Require admin (redirect if not admin)
     */
    public function requireAdmin($redirectTo = 'admin/login.php') {
        if (!$this->isAdmin()) {
            header("Location: {$redirectTo}");
            exit;
        }
    }

    /**
     * Get session ID for anonymous users
     */
    public function getSessionId() {
        if (!isset($_SESSION['session_id'])) {
            $_SESSION['session_id'] = session_id();
        }
        return $_SESSION['session_id'];
    }
}
?>

