<?php
defined('BASEPATH') or exit('No direct script access allowed');

class AuthController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->library('firebase');
        $this->load->helper('url');
    }
    /**
     * Save FCM token sent from admin browser
     */
    public function saveFcmToken()
    {
        $this->output->set_content_type('application/json');

        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);

        if (!isset($input['token']) || empty($input['token'])) {
            echo json_encode(['success' => false, 'message' => 'No token provided']);
            return;
        }

        $token = $input['token'];


        // Use Firebase library function
        $this->load->library('firebase');
        $updated = $this->firebase->saveAdminFcmToken($token);

        if ($updated) {
            echo json_encode(['success' => true, 'message' => 'FCM token saved']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save token']);
        }
    }

    /**
     * Display login page
     */
    public function login()
    {
        // If already logged in, redirect to dashboard
        if ($this->session->userdata('logged_in')) {
            redirect('welcome');
        }

        $this->load->view('admin/login');
    }

    /**
     * Process login request
     */
    public function processLogin()
    {
        $this->output->set_content_type('application/json');

        // Get POST data
        $email = $this->input->post('email', true);
        $password = $this->input->post('password', true);

        // Validate input
        if (empty($email) || empty($password)) {
            echo json_encode([
                'success' => false,
                'message' => 'Please enter both email and password'
            ]);
            return;
        }

        // Validate email format
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid email format'
            ]);
            return;
        }

        // Get user from Firebase by email
        $user = $this->getUserByEmail($email);


        // Check if user exists
        if (!$user) {
            echo json_encode([
                'success' => false,
                'message' => 'Email not found'
            ]);
            return;
        }

        // Verify password (assuming password is stored as plain text in your Firebase)
        // For production, use password_verify() with hashed passwords
        if ($user['password'] !== $password) {
            echo json_encode([
                'success' => false,
                'message' => 'Incorrect password'
            ]);
            return;
        }

        // Check if user is admin
        if (!isset($user['userType']) || $user['userType'] !== 'admin') {
            echo json_encode([
                'success' => false,
                'message' => 'Access denied. Admin privileges required'
            ]);
            return;
        }

        // Set session data
        $sessionData = [
            'user_id' => $user['id'],
            'email' => $user['email'],
            'name' => $user['name'] ?? 'Admin',
            'userType' => $user['userType'],
            'logged_in' => true
        ];
        $this->session->set_userdata($sessionData);

        // Success response
        echo json_encode([
            'success' => true,
            'message' => 'Login successful!',
            'redirect' => base_url('welcome')
        ]);
    }

    /**
     * Logout user
     */
    public function logout()
    {
        // Destroy session
        $this->session->unset_userdata(['user_id', 'email', 'name', 'userType', 'logged_in']);
        $this->session->sess_destroy();

        // Set flash message
        $this->session->set_flashdata('logout_message', 'You have been logged out successfully');

        // Redirect to login
        redirect('admin/login');
    }

    /**
     * Get user by email from Firebase
     * 
     * @param string $email
     * @return array|null
     */
    private function getUserByEmail($email)
    {
        try {
            // Get all users from 'users' collection
            $users = $this->firebase->getCollection('admin');

            // Search for user with matching email
            foreach ($users as $userId => $userData) {
                if (isset($userData['email']) && $userData['email'] === $email) {
                    $userData['id'] = $userId;
                    return $userData;
                }
            }

            return null;
        } catch (Exception $e) {
            log_message('error', 'Firebase getUserByEmail error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Check if user is logged in (helper method for other controllers)
     */
    public function checkAuth()
    {
        if (!$this->session->userdata('logged_in')) {
            redirect('admin/login');
        }
    }
}
