<?php
// coordinator/profile.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/coordinator_auth.php';

$db = null;
if (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
} elseif (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
}

if (!$db) {
    http_response_code(500);
    exit('Database connection not found.');
}

$db->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function cp_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function cp_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

function cp_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (cp_col_exists($db, $table, $col)) {
            return $col;
        }
    }
    return null;
}

$userId = (int)($_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? ($_SESSION['user']['id'] ?? 0));
$profile = [
    'id'       => $userId,
    'name'     => $_SESSION['user_name'] ?? $_SESSION['admin_name'] ?? ($_SESSION['user']['name'] ?? 'Coordinator'),
    'username' => $_SESSION['user']['username'] ?? '',
    'email'    => $_SESSION['user']['email'] ?? '',
    'role'     => 'coordinator',
    'status'   => 'Active',
    'branch'   => '',
    'created'  => '',
];

$error = '';

$userTable = '';
if (cp_table_exists($db, 'elms_users')) {
    $userTable = 'elms_users';
} elseif (cp_table_exists($db, 'users')) {
    $userTable = 'users';
}

if ($userId > 0 && $userTable !== '') {
    $nameCol     = cp_first_col($db, $userTable, ['full_name', 'name', 'display_name']);
    $usernameCol = cp_first_col($db, $userTable, ['username', 'user_name']);
    $emailCol    = cp_first_col($db, $userTable, ['email', 'email_address']);
    $roleCol     = cp_first_col($db, $userTable, ['role_slug', 'role', 'role_code']);
    $statusCol   = cp_first_col($db, $userTable, ['status', 'is_active']);
    $branchCol   = cp_first_col($db, $userTable, ['branch_id', 'branch_ids']);
    $createdCol  = cp_first_col($db, $userTable, ['created_at', 'created_on', 'date_created']);

    $select = ['id'];
    if ($nameCol)     $select[] = "`{$nameCol}` AS profile_name";
    if ($usernameCol) $select[] = "`{$usernameCol}` AS profile_username";
    if ($emailCol)    $select[] = "`{$emailCol}` AS profile_email";
    if ($roleCol)     $select[] = "`{$roleCol}` AS profile_role";
    if ($statusCol)   $select[] = "`{$statusCol}` AS profile_status";
    if ($branchCol)   $select[] = "`{$branchCol}` AS profile_branch";
    if ($createdCol)  $select[] = "`{$createdCol}` AS profile_created";

    $sql = "SELECT " . implode(', ', $select) . " FROM `{$userTable}` WHERE id = ? LIMIT 1";
    $stmt = $db->prepare($sql);

    if ($stmt) {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($row) {
            if (!empty($row['profile_name'])) {
                $profile['name'] = (string)$row['profile_name'];
            }
            if (!empty($row['profile_username'])) {
                $profile['username'] = (string)$row['profile_username'];
            }
            if (!empty($row['profile_email'])) {
                $profile['email'] = (string)$row['profile_email'];
            }
            if (!empty($row['profile_role'])) {
                $profile['role'] = (string)$row['profile_role'];
            }
            if (isset($row['profile_status'])) {
                $statusRaw = (string)$row['profile_status'];
                if ($statusRaw === '1') {
                    $profile['status'] = 'Active';
                } elseif ($statusRaw === '0') {
                    $profile['status'] = 'Inactive';
                } else {
                    $profile['status'] = $statusRaw !== '' ? $statusRaw : 'Active';
                }
            }
            if (!empty($row['profile_branch'])) {
                $profile['branch'] = (string)$row['profile_branch'];
            }
            if (!empty($row['profile_created'])) {
                $profile['created'] = (string)$row['profile_created'];
            }
        }
    } else {
        $error = 'Profile SQL error: ' . $db->error;
    }
}

$branchText = '-';

$branchIdsRaw = $_SESSION['branch_ids'] ?? ($_SESSION['user']['branch_ids'] ?? $profile['branch']);
$branchIds = [];

if (is_array($branchIdsRaw)) {
    $branchIds = array_values(array_filter(array_map('intval', $branchIdsRaw)));
} elseif (is_string($branchIdsRaw) && trim($branchIdsRaw) !== '') {
    $decoded = json_decode($branchIdsRaw, true);
    if (is_array($decoded)) {
        $branchIds = array_values(array_filter(array_map('intval', $decoded)));
    } else {
        $branchIds = array_values(array_filter(array_map('intval', explode(',', $branchIdsRaw))));
    }
}

if (!$branchIds && !empty($_SESSION['branch_id'])) {
    $branchIds[] = (int)$_SESSION['branch_id'];
}

$branchIds = array_values(array_unique(array_filter($branchIds)));

if ($branchIds) {
    $branchNames = [];

    if (cp_table_exists($db, 'branches')) {
        $branchNameCol = cp_first_col($db, 'branches', ['branch_name', 'name', 'title']);
        if ($branchNameCol) {
            $ph = implode(',', array_fill(0, count($branchIds), '?'));
            $types = str_repeat('i', count($branchIds));
            $sql = "SELECT `{$branchNameCol}` AS branch_name FROM branches WHERE id IN ({$ph}) ORDER BY id ASC";
            $stmt = $db->prepare($sql);
            if ($stmt) {
                $stmt->bind_param($types, ...$branchIds);
                $stmt->execute();
                $res = $stmt->get_result();
                while ($r = $res->fetch_assoc()) {
                    $branchNames[] = (string)$r['branch_name'];
                }
                $stmt->close();
            }
        }
    }

    if (!$branchNames && cp_table_exists($db, 'centres')) {
        $centreNameCol = cp_first_col($db, 'centres', ['centre_name', 'center_name', 'name', 'title']);
        if ($centreNameCol) {
            $ph = implode(',', array_fill(0, count($branchIds), '?'));
            $types = str_repeat('i', count($branchIds));
            $sql = "SELECT `{$centreNameCol}` AS branch_name FROM centres WHERE id IN ({$ph}) ORDER BY id ASC";
            $stmt = $db->prepare($sql);
            if ($stmt) {
                $stmt->bind_param($types, ...$branchIds);
                $stmt->execute();
                $res = $stmt->get_result();
                while ($r = $res->fetch_assoc()) {
                    $branchNames[] = (string)$r['branch_name'];
                }
                $stmt->close();
            }
        }
    }

    $branchText = $branchNames ? implode(', ', $branchNames) : implode(', ', array_map(fn($v) => 'Branch #' . $v, $branchIds));
} elseif (!empty($profile['branch'])) {
    $branchText = (string)$profile['branch'];
}

$roleDisplay = ucwords(str_replace(['_', '-'], ' ', (string)$profile['role']));

require_once __DIR__ . '/../includes/coordinator_layout_top.php';
?>

<div class="d-flex justify-content-between align-items-start mb-4">
    <div>
        <h1 class="page-title">My Profile</h1>
        <div class="page-subtitle">Coordinator account details and access information</div>
    </div>

    <a href="/elms/coordinator/dashboard.php" class="btn btn-light border rounded-4">
        <i class="bi bi-arrow-left me-1"></i> Dashboard
    </a>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger rounded-4">
        <strong>Error:</strong> <?= h($error) ?>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="eden-card p-4 text-center">
            <div style="width:88px;height:88px;border-radius:28px;background:#b91c1c;color:#fff;display:flex;align-items:center;justify-content:center;font-size:34px;font-weight:900;margin:0 auto 16px;">
                <?= h(strtoupper(substr((string)$profile['name'], 0, 1))) ?>
            </div>

            <h4 class="fw-bold mb-1"><?= h($profile['name']) ?></h4>
            <div class="text-muted mb-3"><?= h($roleDisplay) ?></div>

            <span class="badge text-bg-danger rounded-pill px-3 py-2">
                Coordinator
            </span>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="eden-card p-4">
            <h5 class="fw-bold mb-3">Account Information</h5>

            <div class="row g-3">
                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">User ID</div>
                        <div class="fw-bold">#<?= (int)$profile['id'] ?></div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Status</div>
                        <div class="fw-bold"><?= h(ucwords((string)$profile['status'])) ?></div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Username</div>
                        <div class="fw-bold"><?= $profile['username'] !== '' ? h($profile['username']) : '<span class="text-muted">-</span>' ?></div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Email</div>
                        <div class="fw-bold"><?= $profile['email'] !== '' ? h($profile['email']) : '<span class="text-muted">-</span>' ?></div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Role</div>
                        <div class="fw-bold"><?= h($roleDisplay) ?></div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Assigned Branch / Centre</div>
                        <div class="fw-bold"><?= h($branchText) ?></div>
                    </div>
                </div>

                <div class="col-md-12">
                    <div class="border rounded-4 p-3 bg-light">
                        <div class="text-muted small">Created Date</div>
                        <div class="fw-bold">
                            <?= $profile['created'] !== '' ? h(date('Y-m-d H:i', strtotime((string)$profile['created']))) : '<span class="text-muted">-</span>' ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="eden-card p-4 mt-4">
            <h5 class="fw-bold mb-3">Coordinator Permissions</h5>

            <div class="row g-2">
                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-check-circle text-success me-1"></i> View assigned batches
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-check-circle text-success me-1"></i> View assessments
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-check-circle text-success me-1"></i> Check submissions
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-check-circle text-success me-1"></i> View reports
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-x-circle text-danger me-1"></i> No system settings access
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 border rounded-4">
                        <i class="bi bi-x-circle text-danger me-1"></i> No user role management
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/coordinator_layout_bottom.php'; ?>