<?php
// ============================================================
//  config/db.php
// ============================================================

// ─── APNI DB DETAILS YAHAN BHARO ────────────────────────────
define('DB_HOST',    'localhost');
define('DB_USER',    'u427625983_schoolinmycity');        // cPanel pe: u427625983_schoolinmycity
define('DB_PASS',    'K#$%^tfvgyt657guvgGG');            // apna DB password
define('DB_NAME',    'u427625983_schoolinmycity');// cPanel pe: u427625983_schoolinmycity
define('DB_CHARSET', 'utf8mb4');
// ─────────────────────────────────────────────────────────────

define('UPLOAD_BASE',         rtrim(str_replace('\\', '/', __DIR__ . '/../uploads'), '/') . '/');
define('MAX_FILE_SIZE',       50 * 1024 * 1024);
define('ALLOWED_MANUSCRIPT',  ['doc','docx','tex','bib','pdf']);
define('ALLOWED_FIGURES',     ['tif','tiff','jpg','jpeg','png']);
define('ALLOWED_OTHER',       ['doc','docx','pdf','jpg','png','xlsx','mp4','mp3']);
define('SESSION_LIFETIME',    7200);


// PayPal sandbox credentials (replace with your sandbox keys)
define('PAYPAL_CLIENT_ID', 'AS0SV3-_cSltPKuxk4YvK1mVtOlpyUg-Da_3KnHigG9rsnL25zXKwmKqxldguo9-bDUrbfeXCt3C10nH');
define('PAYPAL_SECRET', 'EDWiTVAeOwk0gHdHUFuenzZznNTpYfUHTD-AqZRdNTylN2w4p8TDuwi1-QItl42c81DHB5gDmJ2_DH2S');

define('RAZORPAY_KEY_ID', 'rzp_test_ROyv68NRW2LeMD');
define('RAZORPAY_SECRET', 'BsXP1hLj0nKjVZL1RbU83PuT');

// Stripe Configuration
define('STRIPE_PUBLIC_KEY', 'pk_test_51MUPOkSDX9TVziH5BM4KzMyIwqYw9IEqNxzOLXiLsbiIPoQNseHzSfXWxa8GKpWEmI83ohTMpdQNfXBxXodVnFJ0000jEtY1JU'); // Replace with your actual key
define('STRIPE_SECRET_KEY', 'sk_test_51MUPOkSDX9TVziH564g36z2EmlJ6plKjGrHu0P8Ve9Brv4cjnHyQOPUDHBR2iNYHpUa8NVhYzRDCqNbp32JKUGGz006wKK475m'); // Replace with your actual key
define('STRIPE_WEBHOOK_SECRET', 'rk_test_51MUPOkSDX9TVziH5wi8mlzLVlMsO3J77wzgPtFkOEARWiWXvn1T5FVuzFw7sJcP1JjvyUnKgaxTluSqhaWAa0GQF0063EwEEaX'); // Replace with your webhook secret

// Site Configuration
define('SITE_URL', 'https://communeglobal.com');
define('STRIPE_SUCCESS_URL', SITE_URL . '/stripe_success.php');
define('STRIPE_CANCEL_URL', SITE_URL . '/stripe_cancel.php');

define('GROQ_API_KEY','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');

// PayPal base URLs
define('PAYPAL_API_URL', 'https://api-m.sandbox.paypal.com'); // sandbox
// define('PAYPAL_API_URL', 'https://api-m.paypal.com'); // sandbox
define('PAYPAL_BASE', 'https://api-m.paypal.com'); // live
// for production use: https://api-m.paypal.com







/* ── PDO singleton ── */
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
        try {
            // $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            //     PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            //     PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            //     PDO::ATTR_EMULATE_PREPARES   => false,
            // ]);
            
            
            // $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            //     PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            //     PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            //     PDO::ATTR_EMULATE_PREPARES   => false,
            // ]);
            // $pdo->exec("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'");
            
            $pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
            // ← ADD THIS ONE LINE:
            $pdo->exec("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'");
            
        } catch (PDOException $e) {
            http_response_code(500);
            die(json_encode(['success'=>false,'message'=>'DB error: '.$e->getMessage()]));
        }
    }
    return $pdo;
}


/* ── Session ── */
function startSession(): void {
    if (session_status() === PHP_SESSION_NONE) {
        session_set_cookie_params([
            'lifetime' => SESSION_LIFETIME,
            'path'     => '/',
            'secure'   => false,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        session_start();
    }
}

/* ── JSON helper ── */
function jsonResponse(bool $success, string $message = '', array $data = []): void {
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success'=>$success,'message'=>$message], $data));
    exit;
}

/* ── Remember-me cookie login ── */
function _loginFromRememberToken(string $token): void {
    $hash = hash('sha256', $token);
    try {
        $q = db()->prepare(
            "SELECT user_id FROM remember_tokens
             WHERE token_hash=? AND expires_at > NOW() LIMIT 1"
        );
        $q->execute([$hash]);
        $row = $q->fetch();
        if ($row) {
            $_SESSION['user_id']    = $row['user_id'];
            $_SESSION['logged_in']  = true;
            $_SESSION['login_time'] = time();
        }
    } catch(PDOException $e){}
}

/* ── isLoggedIn ── */
function isLoggedIn(): bool {
    startSession();
    if (!empty($_SESSION['user_id'])) return true;
    if (!empty($_COOKIE['remember_token'])) {
        _loginFromRememberToken($_COOKIE['remember_token']);
        return !empty($_SESSION['user_id']);
    }
    return false;
}

/* ── getCurrentUserId ── */
function getCurrentUserId(): int {
    startSession();

    if (empty($_SESSION['user_id']) && !empty($_COOKIE['remember_token'])) {
        _loginFromRememberToken($_COOKIE['remember_token']);
    }

    if (!empty($_SESSION['user_id'])) {
        return (int)$_SESSION['user_id'];
    }

    // Not logged in
    $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
              str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') ||
              str_contains($_SERVER['REQUEST_URI']   ?? '', 'ajax/');
    if ($isAjax) {
        // jsonResponse(false, 'Session expired. Please log in.', ['redirect'=>'login.php']);
        jsonResponse(false, 'Session expired. Please log in.', ['redirect'=>'/author/login.php']);

    }
    $current = urlencode($_SERVER['REQUEST_URI'] ?? '');
    header("Location: login.php?msg=session_expired&redirect=$current");
    exit;
}

/* ── getCurrentUser ── */
function getCurrentUser(): array {
    $uid = getCurrentUserId();
    try {
        $stmt = db()->prepare("SELECT * FROM users WHERE user_id=?");
        $stmt->execute([$uid]);
        $u = $stmt->fetch();
        if ($u) return $u;
    } catch(PDOException $e){}
    session_destroy();
    header('Location: login.php?msg=session_expired');
    exit;
}