<?php
// ============================================================
//  includes/db.php — Database Connection + Helpers
//  Works from ANY directory depth (root, /admin/, /user/)
//  Include with: require_once __DIR__ . '/includes/db.php';
//           or:  require_once dirname(__DIR__) . '/includes/db.php';
// ============================================================

// ── Database Configuration ────────────────────────────────────
define('DB_HOST',    'localhost');
define('DB_NAME',    'admin_panel_db');
define('DB_USER',    'root');      // ← Change to your MySQL username
define('DB_PASS',    '');          // ← Change to your MySQL password
define('DB_CHARSET', 'utf8mb4');

// ── Session & Auth Constants ──────────────────────────────────
define('SESSION_LIFETIME',      3600);  // Admin session: 1 hour
define('USER_SESSION_LIFETIME', 7200);  // User session:  2 hours
define('ADMIN_SESSION_KEY',     'admin_logged_in');
define('USER_SESSION_KEY',      'user_logged_in');

// ── App Config ────────────────────────────────────────────────
define('APP_NAME',    'WADATA Skill Acquisition Center');
define('APP_URL',     'http://localhost/Wadata Skills');  // ← Change for production
define('AVATAR_DIR',  'assets/images/avatars/');
define('MAX_UPLOAD',  2 * 1024 * 1024); // 2MB

// ── PDO Singleton ─────────────────────────────────────────────
function db(): PDO {
    static $pdo = null;

    if ($pdo === null) {
        $dsn = sprintf(
            'mysql:host=%s;dbname=%s;charset=%s',
            DB_HOST, DB_NAME, DB_CHARSET
        );
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];
        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            error_log('[DB ERROR] ' . $e->getMessage());
            // Show friendly error instead of crashing
            http_response_code(503);
            die('<!DOCTYPE html><html><head><title>Service Unavailable</title>
                <style>body{font-family:sans-serif;display:grid;place-items:center;height:100vh;margin:0;background:#0B2545;color:#fff}
                .box{text-align:center;padding:40px}.box h2{color:#FF6A00;margin-bottom:10px}p{opacity:.7}</style></head>
                <body><div class="box"><h2>Database Connection Failed</h2>
                <p>Please check your database settings in <code>includes/db.php</code></p>
                <p>Make sure XAMPP MySQL is running.</p></div></body></html>');
        }
    }
    return $pdo;
}

// ── Query Helpers ─────────────────────────────────────────────
function db_fetch_all(string $sql, array $params = []): array {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function db_fetch_one(string $sql, array $params = []): ?array {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $row  = $stmt->fetch();
    return $row ?: null;
}

function db_execute(string $sql, array $params = []): int {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->rowCount();
}

function db_last_id(): string {
    return db()->lastInsertId();
}

// ── Flash Message Helpers ─────────────────────────────────────
function flash_set(string $key, string $message): void {
    if (session_status() === PHP_SESSION_NONE) session_start();
    $_SESSION['flash_' . $key] = $message;
}

function flash_get(string $key): string {
    if (session_status() === PHP_SESSION_NONE) session_start();
    $msg = $_SESSION['flash_' . $key] ?? '';
    unset($_SESSION['flash_' . $key]);
    return $msg;
}

// ── Activity Log Helper ───────────────────────────────────────
// Logs both admin actions and system/user-triggered events.
// For system events pass $admin_id = null (uses first super admin).
function log_activity(
    string  $action,
    string  $target_type  = 'user',
    ?int    $target_id    = null,
    ?string $target_name  = null,
    ?string $details      = null,
    ?int    $admin_id     = null,
    string  $action_source = 'admin'
): void {
    try {
        // If no admin_id, use the first super admin as system actor
        if ($admin_id === null) {
            $sa = db_fetch_one("SELECT id FROM admins WHERE role='super_admin' AND status='active' LIMIT 1");
            $admin_id = $sa['id'] ?? null;
        }
        if ($admin_id === null) return; // no admin exists yet, skip

        $ip = $_SERVER['REMOTE_ADDR'] ?? null;

        db_execute(
            "INSERT INTO activity_log
               (admin_id, action_source, action, target_type, target_id, target_name, details, ip_address)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            [$admin_id, $action_source, $action, $target_type, $target_id, $target_name, $details, $ip]
        );
    } catch (Throwable $e) {
        error_log('[LOG ERROR] ' . $e->getMessage());
    }
}

// ── Notification Helper ───────────────────────────────────────
function send_notification(
    int     $user_id,
    string  $title,
    string  $message,
    string  $type     = 'general',
    ?int    $sent_by  = null
): void {
    try {
        db_execute(
            "INSERT INTO notifications (user_id, sent_by, type, title, message)
             VALUES (?, ?, ?, ?, ?)",
            [$user_id, $sent_by, $type, $title, $message]
        );
    } catch (Throwable $e) {
        error_log('[NOTIF ERROR] ' . $e->getMessage());
    }
}

// ── Avatar URL Helper ─────────────────────────────────────────
function avatar_url(string $filename, string $default = 'default_avatar.png', string $base = ''): string {
    $file = (!empty($filename) && $filename !== $default) ? $filename : $default;
    return rtrim($base, '/') . '/' . AVATAR_DIR . htmlspecialchars($file);
}

// ── Settings Loader ───────────────────────────────────────────
function load_settings(): array {
    try {
        $rows = db_fetch_all("SELECT setting_key, setting_value FROM system_settings");
        $out  = [];
        foreach ($rows as $row) {
            $out[$row['setting_key']] = $row['setting_value'];
        }
        return $out;
    } catch (Throwable $e) {
        return [];
    }
}

function save_setting(string $key, string $value, ?int $admin_id = null): void {
    db_execute(
        "UPDATE system_settings SET setting_value = ?, updated_by = ? WHERE setting_key = ?",
        [$value, $admin_id, $key]
    );
}