<?php
class Auth {
    private $db;
    private $session_name = SESSION_NAME;
    
    public function __construct($db) {
        $this->db = $db;
        $this->startSession();
    }
    
    private function startSession() {
        if (session_status() === PHP_SESSION_NONE) {
            session_name($this->session_name);
            session_start();
        }
    }
    
    // Register User
    public function register($email, $password, $name, $company_name) {
        try {
            // Check if email already exists
            $exists = $this->db->selectOne(
                "SELECT id FROM users WHERE email = ?",
                [$email]
            );
            
            if ($exists) {
                return ['success' => false, 'message' => 'Email sudah terdaftar'];
            }
            
            // Hash password
            $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
            
            // Insert user
            $userId = $this->db->insert('users', [
                'email' => $email,
                'password' => $hashedPassword,
                'name' => $name,
                'company_name' => $company_name,
                'role' => 'owner'
            ]);
            
            if ($userId) {
                // Create trial subscription
                $trialEndDate = date('Y-m-d H:i:s', strtotime('+' . SUBSCRIPTION_TRIAL_DAYS . ' days'));
                
                $subId = $this->db->insert('subscriptions', [
                    'user_id' => $userId,
                    'plan_type' => 'monthly',
                    'status' => SUB_TRIAL,
                    'start_date' => date(DATE_FORMAT),
                    'end_date' => date(DATE_FORMAT, strtotime('+' . SUBSCRIPTION_TRIAL_DAYS . ' days')),
                    'amount' => 0,
                    'is_trial' => 1,
                    'trial_ends_at' => $trialEndDate
                ]);
                
                return ['success' => true, 'message' => 'Registrasi berhasil', 'user_id' => $userId];
            }
            
            return ['success' => false, 'message' => 'Gagal membuat akun'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Login User
    public function login($email, $password) {
        try {
            $user = $this->db->selectOne(
                "SELECT * FROM users WHERE email = ? AND is_active = 1",
                [$email]
            );
            
            if (!$user) {
                return ['success' => false, 'message' => 'Email atau password salah'];
            }
            
            if (!password_verify($password, $user['password'])) {
                return ['success' => false, 'message' => 'Email atau password salah'];
            }
            
            // Admin bypass subscription check
            if ($user['role'] !== 'admin') {
                $subscription = $this->db->selectOne(
                    "SELECT * FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
                    [$user['id']]
                );

                if (!$subscription || ($subscription['status'] === SUB_EXPIRED && $subscription['is_trial'] === 0)) {
                    return ['success' => false, 'message' => 'Langganan Anda telah berakhir. Silakan perpanjang langganan'];
                }
            } else {
                $subscription = null;
            }
            
            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['company_name'] = $user['company_name'];
            $_SESSION['subscription_id'] = $subscription['id'] ?? null;
            $_SESSION['subscription_status'] = $subscription['status'] ?? null;
            $_SESSION['login_time'] = time();
            
            // Log activity
            $this->logActivity($user['id'], 'LOGIN', 'User login successfully');
            
            return ['success' => true, 'message' => 'Login berhasil'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    // Logout
    public function logout() {
        $userId = $_SESSION['user_id'] ?? null;
        if ($userId) {
            $this->logActivity($userId, 'LOGOUT', 'User logout');
        }
        session_destroy();
        return true;
    }
    
    // Check if user is logged in
    public function isLoggedIn() {
        return isset($_SESSION['user_id']) && !$this->isSessionExpired();
    }
    
    // Check session timeout
    private function isSessionExpired() {
        if (isset($_SESSION['login_time'])) {
            if (time() - $_SESSION['login_time'] > SESSION_TIMEOUT) {
                session_destroy();
                return true;
            }
        }
        return false;
    }
    
    // Get current user
    public function getCurrentUser() {
        if (!$this->isLoggedIn()) {
            return null;
        }
        return $this->db->selectOne(
            "SELECT * FROM users WHERE id = ?",
            [$_SESSION['user_id']]
        );
    }
    
    // Log activity
    private function logActivity($userId, $action, $description) {
        $this->db->insert('activity_logs', [
            'user_id' => $userId,
            'action' => $action,
            'description' => $description,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
    }
}
