<?php
// 1. Session Start sabse upar hona chahiye
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Debug Mode: Development ke liye temporarily on (production me comment ya off karna)
// ini_set('display_errors', 0); // ← production me 0 rakho
// error_reporting(0);           // ← production me 0 rakho

require('database.php');
require('links.php');
require_once(__DIR__ . '/central-domain-config.php');

// Server Timezone Set
date_default_timezone_set("Asia/Kolkata");

// Global Variable Initialization
$nutype = ''; // Initialize globally taaki functions use kar sakein
$udata = array(); // Initialize to avoid warnings

// ---- DYNAMIC DOMAINS (fetched from Central Manager, with caching + fallback) ----
// Koi bhi future change sirf Central Manager me karo - 100+ websites auto-update
$CENTRAL_API_BASE     = function_exists('get_central_api_domain')     ? rtrim(get_central_api_domain(), '/')     : 'https://pariprint.in';
$CENTRAL_GATEWAY_BASE = function_exists('get_central_gateway_domain') ? rtrim(get_central_gateway_domain(), '/') : 'https://gateway.pdfgod.in';

$pariprint_instant_voter_endpoint = $CENTRAL_API_BASE . '/api-proxy.php';
$pariprint_instant_pan_endpoint   = $CENTRAL_API_BASE . '/api-proxy.php';
$pariprint_instant_dl_endpoint    = $CENTRAL_API_BASE . '/api-proxy.php';
$pariprint_instant_rc_endpoint    = $CENTRAL_API_BASE . '/api-proxy.php';

// Fetch Website Settings Data
$webres = mysqli_query($ahk_conn, "SELECT * FROM settings WHERE id=1 AND status=1");
$webdata = $webres ? mysqli_fetch_assoc($webres) : [];
if (!$webdata) { $webdata = []; }

// ====================== PARI PRINT CONFIGURATION ======================
// API Configuration
$auth_url          = $webdata['auth_url']            ?? 'https://apiadda.in/';
$api_key           = $webdata['api_key']             ?? '';
$secret_key        = $webdata['secret_key']          ?? '';
$pariprint_api_key = $webdata['pariprint_api_key']   ?? 'phk_55e219135b215ac76104c0b0e9eacb7ef7dd14fd';

// Extra endpoints / global vars (safe defaults - used in header / index templates)
$flexsecureapiurl  = $webdata['flexsecureapiurl']    ?? 'goodprintportal.in';
$displayName       = $webdata['displayName']         ?? ($webdata['webname'] ?? 'Good Print Portal');
$allusersforadmin  = 0;  // Will be overridden below with actual count
$totalOrdersCountTrick = 0; // fallback for trick badges

// Count total users (for dashboard "Total Users" card), excluding admin accounts for display (admin accounts not counted in "users" figures usually)
if (!empty($ahk_conn)) {
    $cntQ = @mysqli_query($ahk_conn, "SELECT COUNT(*) AS c FROM users WHERE LOWER(type) != 'admin'");
    if ($cntQ && ($r = mysqli_fetch_assoc($cntQ))) {
        $allusersforadmin = (int)$r['c'];
    }
    // Fallback if above returns 0 / fails - count ALL (including admins) just so dashboard shows correct numbers
    if ($allusersforadmin < 1) {
        $cntQ2 = @mysqli_query($ahk_conn, "SELECT COUNT(*) AS c FROM users");
        if ($cntQ2 && ($r2 = mysqli_fetch_assoc($cntQ2))) $allusersforadmin = (int)$r2['c'];
    }
}

// Count unread messages / notifications for header badges
$query_noforadmin  = 0; // admin notification badge count
$query_foruser     = 0; // user notification badge count
$query_noticadmin  = 0; // legacy fallback (referenced in header)
if (!empty($ahk_conn)) {
    $cntAdmin = @mysqli_query($ahk_conn, "SELECT COUNT(*) AS c FROM contact WHERE reply IS NULL OR reply = ''");
    if ($cntAdmin && ($r = mysqli_fetch_assoc($cntAdmin))) {
        $query_noforadmin = (int)$r['c'];
    }
    if (isset($udata['email']) && $udata['email']) {
        $safeEmail = mysqli_real_escape_string($ahk_conn, $udata['email']);
        $cntUser = @mysqli_query($ahk_conn, "SELECT COUNT(*) AS c FROM contact WHERE email='" . $safeEmail . "' AND (reply IS NOT NULL AND reply != '')");
        if ($cntUser && ($r2 = mysqli_fetch_assoc($cntUser))) {
            $query_foruser = (int)$r2['c'];
        }
    }
}
$query_noticadmin = $query_noforadmin; // legacy alias fallback

// 2. Check User Session and Fetch Data
if (isset($_SESSION['phone']) && !empty($_SESSION['phone'])) {
    $safe_phone = mysqli_real_escape_string($ahk_conn, $_SESSION['phone']);
    $uquery = mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='" . $safe_phone . "'");
    
    if ($uquery) {
        $udata = mysqli_fetch_assoc($uquery);
        $nutype = $udata['type'] ?? 'user'; // Set global user type
    }
}

/*
=====================================================================================
=============================== ALL FUNCTIONS HERE ==================================
=====================================================================================
*/

// Check Session Function
function checkSession()
{
    if (!isset($_SESSION['phone']) || empty($_SESSION['phone'])) {
        header('Location: ../login.php');
        die();
    }
}

// Check Admin (Pass user type as argument - accepts 'admin', 'Administrator', 'superadmin' etc)
// NOTE: Call sites use BOTH checkAdmin (Capital A) and checkadmin (lowercase).
// PHP functions are case-insensitive in global symbol table, but DEFINE BOTH names EXPLICITLY
// to eliminate ANY edge-case opcode cache / symbol-table bugs:
function checkadmin($usertype)
{
    $t = strtolower((string)($usertype ?? ''));
    return ($t === 'admin' || $t === 'administrator' || $t === 'superadmin');
}

// Exact capital-A spelling - 99% of callers use checkAdmin()
if (!function_exists('checkAdmin')) {
    function checkAdmin($usertype) { return checkadmin($usertype); }
}

// Get API Balance Function (Pariprint / Dynamic API Base)
function getAPIBalance()
{
    global $pariprint_api_key;

    $apiBase = (function_exists('get_central_api_domain') ? rtrim(get_central_api_domain(), '/') : 'https://pariprint.in');
    $url = $apiBase . "/api-balance.php?" . http_build_query([
        'api_key' => $pariprint_api_key
    ]);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_USERAGENT => 'goodprintportal.in-getAPIBalance',
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        return "Curl Error: " . $err;
    }

    $data = json_decode($response, true);

    if (isset($data['status']) && $data['status'] === 'success' && isset($data['balance'])) {
        return number_format((float) $data['balance'], 2);
    } elseif (isset($data['message'])) {
        return $data['message'];
    } else {
        return "Invalid Response";
    }
}

// If Admin Check (Using Global Nutype)
function ifadmin()
{
    global $nutype;
    return ($nutype == 'admin');
}

// Query Execute
function ahkQuery($sql)
{
    global $ahk_conn;
    $res = mysqli_query($ahk_conn, $sql);
    return $res;
}

// Count Row Number
function ahkRows($sql)
{
    $query = ahkQuery($sql);
    if ($query === false) {
        error_log("MySQL Query Failed: " . mysqli_error($GLOBALS['ahk_conn']) . " | SQL: $sql");
        return 0;
    }
    return mysqli_num_rows($query);
}

// Fetch Row Data 
function fetchRow($sql)
{
    $res = ahkQuery($sql);
    if ($res) {
        return mysqli_fetch_assoc($res);
    }
    return null;
}

// Get Website data 
function ahkweb($columnName)
{
    $res = fetchRow("SELECT * FROM settings WHERE id=1");
    if ($res && isset($res[$columnName])) {
        echo $res[$columnName];
    } else {
        echo ""; // Default fallback
    }
}

// Get Particular Column Name of table
function getColumn($tableName, $columnName, $Identity)
{
    $sql = "SELECT * FROM " . $tableName . " WHERE " . $Identity;
    if (ahkRows($sql) > 0) {
        $res = fetchRow($sql);
        if (isset($res[$columnName])) {
            echo $res[$columnName];
        } else {
            echo "Column not found";
        }
    } else {
        echo "Data not Found";
    }
}

// Get Safe Value 
function getSafe($value)
{
    global $ahk_conn;
    return mysqli_real_escape_string($ahk_conn, $value);
}

// print Array Function 
function printR($data)
{
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}

// Redirect Function (required params first)
function ahkRedirect($time = 0, $url = '')
{
    // For backward compat: support both new order ahkRedirect($time, $url) AND old order ahkRedirect($url, $time).
    // Detect by type of first arg.
    if (is_string($time) || filter_var($time, FILTER_VALIDATE_URL) || (is_string($time) && $time !== '' && (string)(int)$time !== (string)$time && !is_numeric($time))) {
        // Old signature ahkRedirect($url='...', $time=5) was called
        $_realUrl = (string)$time;
        $_realTime = (int)$url;
    } else {
        $_realTime = (int)$time;
        $_realUrl = (string)$url;
    }
    echo "<script>
        setTimeout(() => {
            window.location = '" . $_realUrl . "';
        }, " . $_realTime . ");
    </script>";
}

// Alert Function
function showAlert($fmsg = '', $smsg = '', $type = 'success')
{
    echo "<script>
        $(function () {
            Swal.fire(
                '" . $fmsg . "',
                '" . $smsg . "',
                '" . $type . "'
            )
        })
    </script>";
}

// Login as Admin Logic
function loginAsadmin()
{
    if (isset($_SESSION['adminasuser']) && $_SESSION['adminasuser'] == true && isset($_SESSION['adminusername'])) {
        $_SESSION['phone'] = $_SESSION['adminusername'];
        unset($_SESSION['adminasuser']);
        unset($_SESSION['adminusername']);
        ahkRedirect('index.php', 1200);
    }
}
?>
