<?php
require_once(__DIR__ . '/../config.php');

class Login extends DBConnection {

    private $settings;

    public function __construct(){
        global $_settings;
        $this->settings = $_settings;
        parent::__construct();
    }

    /* ========= LOGIN ========= */
    public function login(){
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        if(empty($email) || empty($password)){
            return json_encode(['status'=>'failed','msg'=>'Complete todos los campos']);
        }

        $stmt = $this->conn->prepare("
            SELECT *
            FROM users
            WHERE email = ? AND active = 1
            LIMIT 1
        ");
        $stmt->bind_param("s",$email);
        $stmt->execute();
        $res = $stmt->get_result();

        if($res && $res->num_rows === 1){
            $user = $res->fetch_assoc();

            if(!password_verify($password, $user['password'])){
                return json_encode(['status'=>'failed','msg'=>'Credenciales incorrectas']);
            }

            foreach($user as $k=>$v){
                if($k !== 'password'){
                    $this->settings->set_userdata($k,$v);
                }
            }

            // TODOS entran por admin (dashboard por rol se encarga)
            return json_encode([
                'status'=>'success',
                'redirect'=>'admin/'
            ]);
        }

        return json_encode(['status'=>'failed','msg'=>'Credenciales incorrectas']);
    }

    /* ========= LOGOUT ========= */
    public function logout(){
        $this->settings->sess_des();
        header("Location: ".base_url);
        exit;
    }
}

/* ========= ROUTER ========= */
$action = $_GET['f'] ?? '';

$auth = new Login();

switch ($action) {

    case 'login':
        echo $auth->login();
    break;

    case 'logout':
        $auth->logout();
    break;

    default:
        // acceso directo no permitido
        http_response_code(403);
        echo json_encode([
            'status' => 'error',
            'msg' => 'Acceso no permitido'
        ]);
    break;
}

