<?php
/**
 * Tom's Java Jive - Authentication Helper
 */

require_once __DIR__ . '/functions.php';

/**
 * Start secure session
 */
function initSession() {
    if (session_status() === PHP_SESSION_NONE) {
        ini_set('session.cookie_httponly', 1);
        ini_set('session.cookie_secure', isset($_SERVER['HTTPS']));
        ini_set('session.use_strict_mode', 1);
        session_name(SESSION_NAME);
        session_start();
    }
}

/**
 * Admin Authentication
 */
class AdminAuth {
    
    public static function login($email, $password) {
        $admin = db()->fetch(
            "SELECT * FROM admin_users WHERE email = :email",
            ['email' => strtolower($email)]
        );
        
        if (!$admin || !verifyPassword($password, $admin['password_hash'])) {
            return false;
        }
        
        // Update last login
        db()->update('admin_users', 
            ['last_login' => date('Y-m-d H:i:s')], 
            'user_id = :id', 
            ['id' => $admin['user_id']]
        );
        
        // Set session
        $_SESSION['admin'] = [
            'user_id' => $admin['user_id'],
            'email' => $admin['email'],
            'name' => $admin['name'],
            'is_master' => (bool)$admin['is_master'],
            'permissions' => json_decode($admin['permissions'] ?? '[]', true)
        ];
        
        // Regenerate session ID for security
        session_regenerate_id(true);
        
        return true;
    }
    
    public static function logout() {
        unset($_SESSION['admin']);
        session_regenerate_id(true);
    }
    
    public static function isLoggedIn() {
        return isset($_SESSION['admin']['user_id']);
    }
    
    public static function getUser() {
        return $_SESSION['admin'] ?? null;
    }
    
    public static function require() {
        if (!self::isLoggedIn()) {
            if (isAjax()) {
                jsonResponse(['error' => 'Unauthorized'], 401);
            }
            $_SESSION['admin_redirect'] = currentUrl();
            redirect('/admin/login.php');
        }
    }
    
    public static function hasPermission($permission) {
        $admin = self::getUser();
        if (!$admin) return false;
        if ($admin['is_master']) return true;
        return in_array($permission, $admin['permissions'] ?? []);
    }
    
    public static function register($email, $password, $name = null, $isMaster = false) {
        $userId = generateId('admin_');
        
        db()->insert('admin_users', [
            'user_id' => $userId,
            'email' => strtolower($email),
            'password_hash' => hashPassword($password),
            'name' => $name ?? $email,
            'is_admin' => 1,
            'is_master' => $isMaster ? 1 : 0
        ]);
        
        return $userId;
    }
}

/**
 * Customer Authentication
 */
class CustomerAuth {
    
    public static function login($email, $password) {
        $customer = db()->fetch(
            "SELECT * FROM customers WHERE email = :email AND password_hash IS NOT NULL",
            ['email' => strtolower($email)]
        );
        
        if (!$customer || !verifyPassword($password, $customer['password_hash'])) {
            return false;
        }
        
        // Set session
        $_SESSION['customer'] = [
            'customer_id' => $customer['customer_id'],
            'email' => $customer['email'],
            'name' => $customer['name']
        ];
        
        session_regenerate_id(true);
        return true;
    }
    
    public static function logout() {
        unset($_SESSION['customer']);
        session_regenerate_id(true);
    }
    
    public static function isLoggedIn() {
        return isset($_SESSION['customer']['customer_id']);
    }
    
    public static function getUser() {
        return $_SESSION['customer'] ?? null;
    }
    
    public static function getFullUser() {
        if (!self::isLoggedIn()) return null;
        
        return db()->fetch(
            "SELECT customer_id, email, name, phone, shipping_address, billing_address, 
                    wallet_balance, reward_points, addresses, preferences, password_hash, created_at
             FROM customers WHERE customer_id = :id",
            ['id' => $_SESSION['customer']['customer_id']]
        );
    }
    
    public static function require() {
        if (!self::isLoggedIn()) {
            if (isAjax()) {
                jsonResponse(['error' => 'Unauthorized'], 401);
            }
            $_SESSION['redirect_after_login'] = currentUrl();
            redirect('/login.php');
        }
    }
    
    public static function register($email, $password, $name = null, $phone = null) {
        // Check if email exists
        $existing = db()->fetch(
            "SELECT customer_id FROM customers WHERE email = :email",
            ['email' => strtolower($email)]
        );
        
        if ($existing) {
            return ['error' => 'Email already registered'];
        }
        
        $customerId = generateId('cust_');
        
        db()->insert('customers', [
            'customer_id' => $customerId,
            'email' => strtolower($email),
            'password_hash' => hashPassword($password),
            'name' => $name,
            'phone' => $phone
        ]);
        
        // Auto login after registration
        $_SESSION['customer'] = [
            'customer_id' => $customerId,
            'email' => strtolower($email),
            'name' => $name
        ];
        
        return ['success' => true, 'customer_id' => $customerId];
    }
    
    public static function createGuest($email, $name = null, $phone = null) {
        // Check if customer exists
        $existing = db()->fetch(
            "SELECT customer_id FROM customers WHERE email = :email",
            ['email' => strtolower($email)]
        );
        
        if ($existing) {
            return $existing['customer_id'];
        }
        
        $customerId = generateId('cust_');
        
        db()->insert('customers', [
            'customer_id' => $customerId,
            'email' => strtolower($email),
            'name' => $name,
            'phone' => $phone,
            'is_guest' => 1
        ]);
        
        return $customerId;
    }
    
    public static function requestPasswordReset($email) {
        $customer = db()->fetch(
            "SELECT customer_id FROM customers WHERE email = :email AND password_hash IS NOT NULL",
            ['email' => strtolower($email)]
        );
        
        if (!$customer) {
            return false;
        }
        
        $token = bin2hex(random_bytes(32));
        $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        db()->insert('password_reset_tokens', [
            'email' => strtolower($email),
            'token' => $token,
            'user_type' => 'customer',
            'expires_at' => $expiresAt
        ]);
        
        // Send email
        $resetUrl = SITE_URL . '/reset-password.php?token=' . $token;
        $html = "
            <h2>Password Reset Request</h2>
            <p>Click the link below to reset your password:</p>
            <p><a href='{$resetUrl}'>{$resetUrl}</a></p>
            <p>This link will expire in 1 hour.</p>
            <p>If you didn't request this, please ignore this email.</p>
        ";
        
        sendEmail($email, 'Password Reset - ' . SITE_NAME, $html);
        
        return true;
    }
    
    public static function resetPassword($token, $newPassword) {
        $reset = db()->fetch(
            "SELECT * FROM password_reset_tokens 
             WHERE token = :token AND user_type = 'customer' AND used = 0 AND expires_at > NOW()",
            ['token' => $token]
        );
        
        if (!$reset) {
            return ['error' => 'Invalid or expired token'];
        }
        
        // Update password
        db()->update('customers',
            ['password_hash' => hashPassword($newPassword)],
            'email = :email',
            ['email' => $reset['email']]
        );
        
        // Mark token as used
        db()->update('password_reset_tokens',
            ['used' => 1],
            'id = :id',
            ['id' => $reset['id']]
        );
        
        return ['success' => true];
    }
}

// Initialize session on include
initSession();
