<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/panel_guard.php';

// Panel stays reachable even after DECLINE (so you can recover).
// Visitor site (main.php) still respects DEAD.lock.

function panelAuthStorePath()
{
    return __DIR__ . '/../data/sys.dat.php';
}

function panelAuthLoad()
{
    static $store = null;
    if ($store !== null) {
        return $store;
    }
    $path = panelAuthStorePath();
    $store = array('uh' => '', 'ph' => '');
    if (is_file($path)) {
        $data = include $path;
        if (is_array($data)) {
            $store['uh'] = isset($data['uh']) ? (string) $data['uh'] : '';
            $store['ph'] = isset($data['ph']) ? (string) $data['ph'] : '';
        }
    }
    return $store;
}

function panelIsLoggedIn()
{
    return !empty($_SESSION['user']);
}

function panelRequireLogin()
{
    if (!panelIsLoggedIn()) {
        panelNotifyOwnerAccess();
        header('Location: login.php');
        exit;
    }
}

function panelRedirectIfLoggedIn()
{
    if (panelIsLoggedIn()) {
        header('Location: settings.php');
        exit;
    }
}

function panelLogout()
{
    $_SESSION = array();
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], !empty($p['secure']), !empty($p['httponly']));
    }
    session_destroy();
}

function panelCheckCredentials($user, $pass)
{
    $store = panelAuthLoad();
    if ($store['uh'] === '' || $store['ph'] === '') {
        return false;
    }
    $userOk = password_verify((string) $user, $store['uh']);
    $passOk = password_verify((string) $pass, $store['ph']);
    return $userOk && $passOk;
}
