<?php
// BASE URL untuk aplikasi ios web - Dynamic detection
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host     = $_SERVER['HTTP_HOST'] ?? 'localhost';

/**
 * Path web ke folder `public` CI4 (tanpa trailing slash).
 * Ubah jika project tidak di bawah `/bij-migration/bij.mwp.co.id-ci4/public`.
 */
$dev_ci4_public_web_path = '/bij-migration/bij.mwp.co.id-ci4/public';

/**
 * true = API JSON & URL aset (SITE_PUBLIC_URL) selalu ke produksi https://bij.mwp.co.id
 * walau halaman PHP dibuka dari localhost / Live Preview.
 * false = API mengikuti host (Laragon) kecuali host sudah bij.mwp.co.id.
 */
$ios_force_production_api = true;

$host_is_bij_production = strpos($host, 'bij.mwp.co.id') !== false;
$use_production_api    = $ios_force_production_api || $host_is_bij_production;

if ($host_is_bij_production) {
    define('BASE_URL', 'https://bij.mwp.co.id/ios/app/');
} else {
    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/'));
    define('BASE_URL', $protocol . '://' . $host . rtrim($scriptDir, '/') . '/');
}

if ($use_production_api) {
    define('API_BASE', 'https://bij.mwp.co.id/json/');
    /** Akar situs produksi (assets/uploads/… dari web root) */
    define('SITE_PUBLIC_URL', 'https://bij.mwp.co.id');
} else {
    /** Mobile JSON CI4: route group `json` → …/public/index.php/json/{method} */
    define('API_BASE', $protocol . '://' . $host . $dev_ci4_public_web_path . '/index.php/json/');
    define('SITE_PUBLIC_URL', $protocol . '://' . $host . $dev_ci4_public_web_path);
}

/**
 * URL gambar berita (assets/uploads/berita/). Kosong jika tidak ada file.
 */
function uploads_berita_url(string $photo): string
{
    $p = trim($photo);
    if ($p === '' || $p === '-') {
        return '';
    }
    if (preg_match('#^https?://#i', $p)) {
        return $p;
    }
    $p = str_replace('\\', '/', $p);

    return rtrim(SITE_PUBLIC_URL, '/') . '/assets/uploads/berita/' . rawurlencode(basename($p));
}

/**
 * URL foto profil pegawai (assets/uploads/pengguna/).
 */
function uploads_pengguna_url(string $photo): string
{
    $p = trim($photo);
    if ($p === '' || $p === '-') {
        return '';
    }
    if (preg_match('#^https?://#i', $p)) {
        return $p;
    }
    $p = str_replace('\\', '/', $p);

    return rtrim(SITE_PUBLIC_URL, '/') . '/assets/uploads/pengguna/' . rawurlencode(basename($p));
}

/**
 * True jika kolom waktu presensi benar-benar terisi (bukan placeholder 00:00 / 00:00:00).
 * DB/MySQL sering mengembalikan TIME sebagai "00:00:00" walau belum rekam — jangan anggap sudah absen.
 */
function presensi_waktu_terisi($value): bool
{
    if ($value === null) {
        return false;
    }
    if (is_string($value)) {
        $value = trim($value);
        if ($value === '' || strcasecmp($value, 'null') === 0 || $value === '-') {
            return false;
        }
    }

    $h = 0;
    $m = 0;
    $s = 0;

    if (is_string($value) && preg_match('/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/', $value, $parts)) {
        $h = (int) $parts[1];
        $m = (int) $parts[2];
        $s = isset($parts[3]) ? (int) $parts[3] : 0;
    } elseif (is_string($value) && strpos($value, ':') !== false) {
        $ts = strtotime($value);
        if ($ts === false) {
            return false;
        }
        $h = (int) date('H', $ts);
        $m = (int) date('i', $ts);
        $s = (int) date('s', $ts);
    } else {
        return false;
    }

    return ! ($h === 0 && $m === 0 && $s === 0);
}

// API Endpoints
define('API_LOGIN', 'login');
define('API_LOGIN_TOKEN', 'login_w_token');
define('API_PROFIL', 'profil');
define('API_SAVE_PP', 'save_pp');
define('API_SAVE_MASUK', 'save_masuk');
define('API_SAVE_PULANG', 'save_pulang');
define('API_SAVE_ISTIRAHAT', 'save_istirahat');
define('API_PRESENSI', 'presensi');
define('API_PRESENSI_TODAY', 'presensi_today');
define('API_CUTI', 'cuti');
define('API_SAVE_CUTI', 'save_cuti');
define('API_BATALKAN_CUTI', 'batalkan_cuti');
define('API_LEMBUR', 'lembur');
define('API_BERITA', 'berita');
define('API_LIBUR', 'libur');

// Helper function untuk URL
function url($path = '')
{
    return BASE_URL . ltrim($path, '/');
}

// Helper function untuk asset URL
function asset($path = '')
{
    return BASE_URL . 'assets/' . ltrim($path, '/');
}

/** URL file di web root CI4 `public` (mis. favicon logo). */
function site_public_asset(string $path): string
{
    return rtrim(SITE_PUBLIC_URL, '/') . '/' . ltrim($path, '/');
}


// Helper function biar makin gampang
function api_request($endpoint, $token = null, $body = null)
{
    $ch = curl_init(API_BASE . $endpoint);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    ]);

    if ($body) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    }

    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['error' => true, 'message' => 'CURL Error: ' . $error];
    }

    $data = json_decode($res, true);

    $success = false;
    if ($httpCode >= 200 && $httpCode < 300) {
        if (isset($data['status'])) {
            $success = ($data['status'] == 1);
        } else {
            $success = true;
        }
    }

    return [
        'success' => $success,
        'http_code' => $httpCode,
        'data' => $data,
        'raw_response' => $res
    ];
}

// Helper function untuk login
function api_login($username, $password)
{
    // Coba format yang berbeda
    $data = [
        'username' => $username,
        'password' => $password
    ];

    error_log("Login data: " . json_encode($data));

    return api_request(API_LOGIN, null, $data);
}

// Helper function untuk silent login dengan token
function api_login_token($token)
{
    return api_request(API_LOGIN_TOKEN, $token);
}

// Helper function untuk get profil
function api_get_profil($token)
{
    return api_request(API_PROFIL, null, ['token' => $token]);
}

// Helper function untuk save presensi masuk
function api_save_masuk($token, $data)
{
    $data['token'] = $token;
    return api_request(API_SAVE_MASUK, null, $data);
}

// Helper function untuk save presensi pulang
function api_save_pulang($token, $data)
{
    $data['token'] = $token;
    return api_request(API_SAVE_PULANG, null, $data);
}

// Helper function untuk save istirahat
function api_save_istirahat($token, $data)
{
    $data['token'] = $token;
    return api_request(API_SAVE_ISTIRAHAT, null, $data);
}

// Helper function untuk get riwayat presensi
function api_get_presensi($token)
{
    return api_request(API_PRESENSI, null, ['token' => $token]);
}

// Helper function untuk get presensi hari ini
function api_get_presensi_today($token)
{
    return api_request(API_PRESENSI_TODAY, null, ['token' => $token]);
}

// Helper function untuk get cuti
function api_get_cuti($token)
{
    return api_request(API_CUTI, null, ['token' => $token]);
}

// Helper function untuk save cuti
function api_save_cuti($token, $data)
{
    $data['token'] = $token;
    return api_request(API_SAVE_CUTI, null, $data);
}

// Helper function untuk batalkan cuti
function api_batalkan_cuti($token, $data)
{
    $data['token'] = $token;
    return api_request(API_BATALKAN_CUTI, null, $data);
}

// Helper function untuk get lembur
function api_get_lembur($token)
{
    return api_request(API_LEMBUR, null, ['token' => $token]);
}

// Helper function untuk get berita
function api_get_berita($token)
{
    return api_request(API_BERITA, null, ['token' => $token]);
}

// Helper function untuk get libur
function api_get_libur($token)
{
    return api_request(API_LIBUR, null, ['token' => $token]);
}

// Helper function untuk upload photo profil
function api_save_pp($token, $data)
{
    $data['token'] = $token;
    return api_request(API_SAVE_PP, null, $data);
}
