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

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        
        // CORS headers
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization');
        header('Content-Type: application/json');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->model('User_model');
        $this->load->helper('form');
    }

    /**
     * User login
     * POST /auth/login
     */
     
      public function preflight() {
        $this->output->set_status_header(200)->set_output('');
    }
    
    public function login() {
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
        // Validate required fields
        if (empty($json_data['email']) || empty($json_data['password'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'EMAIL_AND_PASSWORD_REQUIRED'
                )));
        }
        
        $email = $json_data['email'];
        $password = $json_data['password'];
        
        // Verify credentials
        $user = $this->User_model->verify_credentials($email, $password);
        
        if ($user) {
            // Generate token (simple approach - should use JWT in production)
            $token = $this->generate_token($user);
            
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'LOGIN_SUCCESSFUL',
                    'data' => array(
                        'user' => $user,
                        'token' => $token
                    )
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_CREDENTIALS'
                )));
        }
    }

    /**
     * User logout
     * POST /auth/logout
     */
    public function logout() {
        // In a stateless JWT system, logout is handled client-side
        // Just return success
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'LOGOUT_SUCCESSFUL'
            )));
    }

    /**
     * Verify token
     * GET /auth/verify
     */
    public function verify() {
        $headers = $this->input->request_headers();
        
        if (!isset($headers['Authorization'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'AUTHORIZATION_TOKEN_REQUIRED'
                )));
        }
        
        $token = str_replace('Bearer ', '', $headers['Authorization']);
        $user_data = $this->verify_token($token);
        
        if ($user_data) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'TOKEN_VALID',
                    'data' => $user_data
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_TOKEN'
                )));
        }
    }

    /**
     * Change password
     * POST /auth/change-password
     */
    public function change_password() {
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
        // Validate required fields
        if (empty($json_data['email']) || empty($json_data['old_password']) || empty($json_data['new_password'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'MISSING_REQUIRED_FIELDS'
                )));
        }
        
        // Verify old credentials
        $user = $this->User_model->verify_credentials($json_data['email'], $json_data['old_password']);
        
        if ($user) {
            // Update password
            $update_data = array('password' => $json_data['new_password']);
            
            if ($this->User_model->update_user($user['id'], $update_data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'PASSWORD_CHANGED_SUCCESSFULLY'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(500)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FAILED_TO_CHANGE_PASSWORD'
                    )));
            }
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_CREDENTIALS'
                )));
        }
    }

    /**
     * Generate authentication token
     * 
     * WARNING: This is a placeholder implementation using base64 encoding.
     * Base64 is NOT secure and provides no signature verification.
     * MUST be replaced with proper JWT using firebase/php-jwt before production.
     * 
     * Recommended implementation:
     * - Use firebase/php-jwt library
     * - Sign tokens with HMAC-SHA256 or RSA
     * - Set appropriate expiration time
     * - Store secret key securely
     */
    private function generate_token($user) {
        $token_data = array(
            'user_id' => $user['id'],
            'email' => $user['email'],
            'role' => $user['role'],
            'timestamp' => time()
        );
        
        // TODO: Replace with proper JWT implementation
        // This is NOT secure for production use
        return base64_encode(json_encode($token_data));
    }

    /**
     * Verify authentication token
     * 
     * WARNING: This is a placeholder implementation.
     * MUST be replaced with proper JWT verification before production.
     */
    private function verify_token($token) {
        try {
            $decoded = json_decode(base64_decode($token), true);
            
            if ($decoded && isset($decoded['user_id'])) {
                // Get fresh user data
                $user = $this->User_model->get_user_by_id($decoded['user_id']);
                return $user;
            }
            
            return false;
        } catch (Exception $e) {
            return false;
        }
    }
}
