<?php
// ============================================================
//  config/db.php  —  Database Configuration
// ============================================================

define('DB_HOST',     'localhost');
define('DB_USER',     'root');
define('DB_PASS',     '');           // apna password yahan
define('DB_NAME',     'communeglobal_db');
define('DB_CHARSET',  'utf8mb4');

// Upload settings
// Upload base path — works on both Windows (WAMP) and Linux
define('UPLOAD_BASE', rtrim(str_replace('\\', '/', __DIR__ . '/../uploads'), '/') . '/');
define('MAX_FILE_SIZE', 50 * 1024 * 1024); // 50 MB
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']);

// Session settings
define('SESSION_LIFETIME', 7200); // 2 hours

/**
 * Get PDO database connection (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,
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            die(json_encode([
                'success' => false,
                'message' => 'Database connection failed: ' . $e->getMessage()
            ]));
        }
    }
    return $pdo;
}

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

/**
 * Return JSON response and exit
 */
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;
}

/**
 * Get logged-in user ID (for demo we use session; plug your auth here)
 * Returns hardcoded 1 for testing if not logged in
 */
function getCurrentUserId(): int {
    startSession();
    return $_SESSION['user_id'] ?? 1; // change to auth redirect in production
}

/**
 * Get logged-in user info
 */
function getCurrentUser(): array {
    $uid = getCurrentUserId();
    $stmt = db()->prepare("SELECT * FROM users WHERE user_id = ?");
    $stmt->execute([$uid]);
    return $stmt->fetch() ?: [
        'user_id'    => 1,
        'email'      => 'author@example.com',
        'first_name' => 'Mohit',
        'last_name'  => 'Arora',
        'title'      => 'Dr',
    ];
}