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

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        // Set CORS headers
        $this->_cors();
    }

    private function _cors() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        if ($this->input->server('REQUEST_METHOD') === 'OPTIONS') {
            exit(0);
        }
    }

    private function _json($status, $message, $data = null, $code = 200) {
        http_response_code($code);
        header('Content-Type: application/json');
        $response = ['status' => $status, 'message' => $message];
        if ($data !== null) $response['data'] = $data;
        echo json_encode($response);
        exit;
    }

    public function login() {
        $email    = $this->input->post('email');
        $password = $this->input->post('password');

        if (!$email || !$password) {
            $this->_json(false, 'Email dan password wajib diisi', null, 400);
        }

        $user = $this->User_model->get_by_email($email);

        if (!$user || !password_verify($password, $user->password)) {
            $this->_json(false, 'Email atau password salah', null, 401);
        }

        // Set session
        $this->session->set_userdata([
            'user_id' => $user->id,
            'nama'    => $user->nama,
            'email'   => $user->email,
            'role'    => $user->role,
        ]);

        $this->_json(true, 'Login berhasil', [
            'id'    => $user->id,
            'nama'  => $user->nama,
            'email' => $user->email,
            'role'  => $user->role,
        ]);
    }

    public function register() {
        $nama     = $this->input->post('nama');
        $email    = $this->input->post('email');
        $password = $this->input->post('password');

        if (!$nama || !$email || !$password) {
            $this->_json(false, 'Semua field wajib diisi', null, 400);
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->_json(false, 'Format email tidak valid', null, 400);
        }

        if (strlen($password) < 6) {
            $this->_json(false, 'Password minimal 6 karakter', null, 400);
        }

        if ($this->User_model->email_exists($email)) {
            $this->_json(false, 'Email sudah terdaftar', null, 409);
        }

        $id = $this->User_model->register([
            'nama'  => $nama,
            'email' => $email,
            'password' => $password,
        ]);

        $this->_json(true, 'Registrasi berhasil', ['id' => $id]);
    }

    public function logout() {
        $this->session->sess_destroy();
        $this->_json(true, 'Logout berhasil');
    }

    public function me() {
        $user_id = $this->session->userdata('user_id');
        if (!$user_id) {
            $this->_json(false, 'Unauthorized', null, 401);
        }
        $this->_json(true, 'OK', [
            'user_id' => $this->session->userdata('user_id'),
            'nama'    => $this->session->userdata('nama'),
            'email'   => $this->session->userdata('email'),
            'role'    => $this->session->userdata('role'),
        ]);
    }

    public function stats() {
        $this->load->model('Ebook_model');
        $this->_json(true, 'OK', [
            'total_ebook' => $this->Ebook_model->count_all(),
            'total_user'  => $this->User_model->count_all(),
            'categories'  => $this->Ebook_model->count_by_category(),
        ]);
    }
}
