<?php
/**
 * Authentication Class
 * PSAU GAD Information System
 */

class Auth {
    private $db;
    
    public function __construct() {
        $this->db = getDB();
    }
    
    /**
     * Register new user
     */
    public function register($email, $password, $role = 'employee', $isPsauAccount = false) {
        try {
            // Validate email
            if (!isValidEmail($email)) {
                return ['success' => false, 'message' => 'Invalid email address'];
            }
            
            // Validate password
            if (strlen($password) < PASSWORD_MIN_LENGTH) {
                return ['success' => false, 'message' => 'Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters'];
            }
            
            // Check if email already exists
            $stmt = $this->db->prepare("SELECT user_id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Email already registered'];
            }
            
            // Hash password
            $passwordHash = hashPassword($password);
            
            // Auto-approve PSAU accounts
            $isApproved = $isPsauAccount ? 1 : 0;
            
            // Insert user
            $stmt = $this->db->prepare("
                INSERT INTO users (email, password_hash, role, is_psau_account, is_approved)
                VALUES (?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([$email, $passwordHash, $role, $isPsauAccount ? 1 : 0, $isApproved]);
            $userId = $this->db->lastInsertId();
            
            return [
                'success' => true,
                'message' => $isPsauAccount ? 'Registration successful' : 'Registration successful. Please wait for approval.',
                'user_id' => $userId,
                'requires_approval' => !$isPsauAccount
            ];
            
        } catch (PDOException $e) {
            logError("Registration error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Registration failed'];
        }
    }
    
    /**
     * Login user
     */
    public function login($email, $password) {
        try {
            // Get user
            $stmt = $this->db->prepare("
                SELECT u.*, 
                       CONCAT(ep.first_name, ' ', ep.last_name) as full_name
                FROM users u
                LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
                WHERE u.email = ?
            ");
            $stmt->execute([$email]);
            $user = $stmt->fetch();
            
            if (!$user) {
                return ['success' => false, 'message' => 'Invalid email or password'];
            }
            
            // Verify password
            if (!verifyPassword($password, $user['password_hash'])) {
                return ['success' => false, 'message' => 'Invalid email or password'];
            }
            
            // Check if account is active
            if (!$user['is_active']) {
                return ['success' => false, 'message' => 'Account is deactivated'];
            }
            
            // Check if account is approved
            if (!$user['is_approved']) {
                return ['success' => false, 'message' => 'Account is pending approval'];
            }
            
            // Update last login
            $updateStmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE user_id = ?");
            $updateStmt->execute([$user['user_id']]);
            
            // Set session
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['full_name'] = $user['full_name'] ?? 'User';
            $_SESSION['is_psau_account'] = $user['is_psau_account'];
            $_SESSION['last_activity'] = time();
            
            return [
                'success' => true,
                'message' => 'Login successful',
                'user' => [
                    'user_id' => $user['user_id'],
                    'email' => $user['email'],
                    'role' => $user['role'],
                    'full_name' => $user['full_name']
                ]
            ];
            
        } catch (PDOException $e) {
            logError("Login error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Login failed'];
        }
    }
    
    /**
     * Logout user
     */
    public function logout() {
        session_unset();
        session_destroy();
        return ['success' => true, 'message' => 'Logged out successfully'];
    }
    
    /**
     * Check session timeout
     */
    public function checkSessionTimeout() {
        if (isset($_SESSION['last_activity'])) {
            $elapsed = time() - $_SESSION['last_activity'];
            if ($elapsed > SESSION_TIMEOUT) {
                $this->logout();
                return false;
            }
        }
        $_SESSION['last_activity'] = time();
        return true;
    }
    
    /**
     * Change password
     */
    public function changePassword($userId, $currentPassword, $newPassword) {
        try {
            // Get current password hash
            $stmt = $this->db->prepare("SELECT password_hash FROM users WHERE user_id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            
            if (!$user) {
                return ['success' => false, 'message' => 'User not found'];
            }
            
            // Verify current password
            if (!verifyPassword($currentPassword, $user['password_hash'])) {
                return ['success' => false, 'message' => 'Current password is incorrect'];
            }
            
            // Validate new password
            if (strlen($newPassword) < PASSWORD_MIN_LENGTH) {
                return ['success' => false, 'message' => 'New password must be at least ' . PASSWORD_MIN_LENGTH . ' characters'];
            }
            
            // Update password
            $newPasswordHash = hashPassword($newPassword);
            $updateStmt = $this->db->prepare("UPDATE users SET password_hash = ? WHERE user_id = ?");
            $updateStmt->execute([$newPasswordHash, $userId]);
            
            return ['success' => true, 'message' => 'Password changed successfully'];
            
        } catch (PDOException $e) {
            logError("Change password error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to change password'];
        }
    }
    
    /**
     * Approve user account
     */
    public function approveAccount($userId) {
        try {
            $stmt = $this->db->prepare("UPDATE users SET is_approved = 1 WHERE user_id = ?");
            $stmt->execute([$userId]);
            
            return ['success' => true, 'message' => 'Account approved successfully'];
        } catch (PDOException $e) {
            logError("Approve account error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to approve account'];
        }
    }
    
    /**
     * Reject user account
     */
    public function rejectAccount($userId) {
        try {
            $stmt = $this->db->prepare("UPDATE users SET is_active = 0 WHERE user_id = ?");
            $stmt->execute([$userId]);
            
            return ['success' => true, 'message' => 'Account rejected'];
        } catch (PDOException $e) {
            logError("Reject account error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to reject account'];
        }
    }
    
    /**
     * Get pending account approvals
     */
    public function getPendingApprovals() {
        try {
            $stmt = $this->db->prepare("
                SELECT u.user_id, u.email, u.created_at,
                       CONCAT(ep.first_name, ' ', ep.last_name) as full_name,
                       ep.category, ep.position
                FROM users u
                LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
                WHERE u.is_approved = 0 AND u.is_active = 1
                ORDER BY u.created_at DESC
            ");
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            logError("Get pending approvals error: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Check if email is PSAU account
     */
    public function isPsauEmail($email) {
        return strpos($email, '@psau.edu.ph') !== false;
    }
    
    /**
     * Get user by ID
     */
    public function getUserById($userId) {
        try {
            $stmt = $this->db->prepare("
                SELECT u.*, 
                       ep.*,
                       CONCAT(ep.first_name, ' ', ep.last_name) as full_name
                FROM users u
                LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
                WHERE u.user_id = ?
            ");
            $stmt->execute([$userId]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            logError("Get user by ID error: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Update user profile
     */
    public function updateProfile($userId, $data) {
        try {
            // Check if profile exists
            $stmt = $this->db->prepare("SELECT profile_id FROM employee_profiles WHERE user_id = ?");
            $stmt->execute([$userId]);
            $profile = $stmt->fetch();
            
            if ($profile) {
                // Update existing profile
                $stmt = $this->db->prepare("
                    UPDATE employee_profiles 
                    SET first_name = ?, middle_name = ?, last_name = ?, suffix = ?,
                        gender = ?, date_of_birth = ?, age = ?, position = ?,
                        category = ?, department = ?, contact_number = ?, address = ?
                    WHERE user_id = ?
                ");
                
                $stmt->execute([
                    $data['first_name'],
                    $data['middle_name'] ?? null,
                    $data['last_name'],
                    $data['suffix'] ?? null,
                    $data['gender'],
                    $data['date_of_birth'] ?? null,
                    $data['age'] ?? null,
                    $data['position'] ?? null,
                    $data['category'],
                    $data['department'] ?? null,
                    $data['contact_number'] ?? null,
                    $data['address'] ?? null,
                    $userId
                ]);
            } else {
                // Insert new profile
                $stmt = $this->db->prepare("
                    INSERT INTO employee_profiles 
                    (user_id, first_name, middle_name, last_name, suffix, gender, 
                     date_of_birth, age, position, category, department, contact_number, address)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                
                $stmt->execute([
                    $userId,
                    $data['first_name'],
                    $data['middle_name'] ?? null,
                    $data['last_name'],
                    $data['suffix'] ?? null,
                    $data['gender'],
                    $data['date_of_birth'] ?? null,
                    $data['age'] ?? null,
                    $data['position'] ?? null,
                    $data['category'],
                    $data['department'] ?? null,
                    $data['contact_number'] ?? null,
                    $data['address'] ?? null
                ]);
            }
            
            return ['success' => true, 'message' => 'Profile updated successfully'];
            
        } catch (PDOException $e) {
            logError("Update profile error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Failed to update profile'];
        }
    }
}

