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

require_once __DIR__ . '/../includes/auth.php';
ec_require_login();

$db = ec_db();
if (!$db instanceof mysqli) {
    die('DB connection failed');
}

$ACTIVE = 'profile';

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

function profile_col_exists(mysqli $db, string $table, string $col): bool {
    if (function_exists('col_exists')) {
        return col_exists($db, $table, $col);
    }
    $table = $db->real_escape_string($table);
    $col   = $db->real_escape_string($col);
    $rs = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
    return $rs && $rs->num_rows > 0;
}

function profile_table_exists(mysqli $db, string $table): bool {
    if (function_exists('table_exists')) {
        return table_exists($db, $table);
    }
    $table = $db->real_escape_string($table);
    $rs = $db->query("SHOW TABLES LIKE '{$table}'");
    return $rs && $rs->num_rows > 0;
}

function profile_flash(string $type, string $message): void {
    $_SESSION['profile_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

$current = ec_user();
$userId = (int)($current['id'] ?? 0);

if ($userId <= 0) {
    die('Invalid logged-in user. Please logout and login again.');
}

if (!profile_table_exists($db, 'users')) {
    die('Users table not found.');
}

$errors = [];

$hasUsername   = profile_col_exists($db, 'users', 'username');
$hasAvatar     = profile_col_exists($db, 'users', 'avatar_url');
$hasBranchId   = profile_col_exists($db, 'users', 'branch_id');
$hasBranchName = profile_col_exists($db, 'users', 'branch_name');
$hasCreatedAt  = profile_col_exists($db, 'users', 'created_at');
$hasUpdatedAt  = profile_col_exists($db, 'users', 'updated_at');
$hasLastLogin  = profile_col_exists($db, 'users', 'last_login');
$hasActive     = profile_col_exists($db, 'users', 'active');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name      = trim((string)($_POST['name'] ?? ''));
    $email     = trim((string)($_POST['email'] ?? ''));
    $username  = trim((string)($_POST['username'] ?? ''));
    $avatarUrl = trim((string)($_POST['avatar_url'] ?? ''));

    if ($name === '') {
        $errors[] = 'Name is required.';
    }

    if ($email === '') {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }

    if ($hasUsername && $username === '') {
        $username = $email;
    }

    if (!$errors) {
        $st = $db->prepare("SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1");
        if ($st) {
            $st->bind_param('si', $email, $userId);
            $st->execute();
            $dup = $st->get_result()->fetch_assoc();
            $st->close();

            if ($dup) {
                $errors[] = 'This email is already used by another user.';
            }
        }
    }

    if (!$errors && $hasUsername && $username !== '') {
        $st = $db->prepare("SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1");
        if ($st) {
            $st->bind_param('si', $username, $userId);
            $st->execute();
            $dup = $st->get_result()->fetch_assoc();
            $st->close();

            if ($dup) {
                $errors[] = 'This username is already used by another user.';
            }
        }
    }

    if (!$errors) {
        $sets = ['name = ?', 'email = ?'];
        $types = 'ss';
        $vals = [$name, $email];

        if ($hasUsername) {
            $sets[] = 'username = ?';
            $types .= 's';
            $vals[] = $username;
        }

        if ($hasAvatar) {
            $sets[] = 'avatar_url = ?';
            $types .= 's';
            $vals[] = $avatarUrl;
        }

        if ($hasUpdatedAt) {
            $sets[] = 'updated_at = NOW()';
        }

        $types .= 'i';
        $vals[] = $userId;

        $sql = "UPDATE users SET " . implode(', ', $sets) . " WHERE id = ? LIMIT 1";
        $st = $db->prepare($sql);

        if (!$st) {
            $errors[] = 'Profile update failed: ' . $db->error;
        } else {
            $st->bind_param($types, ...$vals);
            $ok = $st->execute();
            $st->close();

            if ($ok) {
                $_SESSION['user']['name'] = $name;
                $_SESSION['user']['email'] = $email;
                $_SESSION['user']['username'] = $hasUsername ? $username : $email;
                if ($hasAvatar) {
                    $_SESSION['user']['avatar_url'] = $avatarUrl;
                }

                profile_flash('success', 'Profile updated successfully.');
                header('Location: profile.php');
                exit;
            }

            $errors[] = 'Profile update failed.';
        }
    }
}

$select = [
    'u.id',
    'u.name',
    'u.email',
    'u.role_slug',
];

if ($hasUsername)   $select[] = 'u.username';
if ($hasAvatar)     $select[] = 'u.avatar_url';
if ($hasBranchId)   $select[] = 'u.branch_id';
if ($hasBranchName) $select[] = 'u.branch_name';
if ($hasCreatedAt)  $select[] = 'u.created_at';
if ($hasUpdatedAt)  $select[] = 'u.updated_at';
if ($hasLastLogin)  $select[] = 'u.last_login';
if ($hasActive)     $select[] = 'u.active';

$join = '';
if ($hasBranchId && profile_table_exists($db, 'branches')) {
    $join = " LEFT JOIN branches b ON b.id = u.branch_id ";
    $select[] = 'b.name AS real_branch_name';
}

$sql = "SELECT " . implode(', ', $select) . " FROM users u {$join} WHERE u.id = ? LIMIT 1";
$st = $db->prepare($sql);
$st->bind_param('i', $userId);
$st->execute();
$user = $st->get_result()->fetch_assoc();
$st->close();

if (!$user) {
    die('User not found.');
}

$branchName = $user['branch_name'] ?? ($user['real_branch_name'] ?? '—');
$avatar = trim((string)($user['avatar_url'] ?? ''));
if ($avatar === '' || $avatar === '0') {
    $avatar = '/edenrms/assets/img/avatar-default.jpg';
}

$flash = $_SESSION['profile_flash'] ?? null;
unset($_SESSION['profile_flash']);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<main class="ec-main">
    <div class="container-fluid py-4">

        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-4">
            <div>
                <h4 class="mb-1 fw-bold">My Profile</h4>
                <div class="text-muted small">Manage your RMS account information.</div>
            </div>
            <a href="change_password.php" class="btn btn-dark rounded-pill px-4">
                <i class="bi bi-shield-lock me-1"></i> Change Password
            </a>
        </div>

        <?php if ($flash): ?>
            <div class="alert alert-<?= h($flash['type']) ?> alert-dismissible fade show">
                <?= h($flash['message']) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <strong>Please check:</strong>
                <ul class="mb-0 mt-1">
                    <?php foreach ($errors as $e): ?>
                        <li><?= h($e) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                    <div class="card-body text-center p-4">
                        <div class="mx-auto mb-3 rounded-circle overflow-hidden border shadow-sm"
                             style="width:110px;height:110px;background:#f8fafc;">
                            <img src="<?= h($avatar) ?>"
                                 alt="Avatar"
                                 style="width:100%;height:100%;object-fit:cover;"
                                 onerror="this.onerror=null;this.src='/edenrms/assets/img/avatar-default.jpg';">
                        </div>

                        <h5 class="fw-bold mb-1"><?= h($user['name'] ?? 'User') ?></h5>
                        <div class="text-muted small mb-3"><?= h($user['email'] ?? '') ?></div>

                        <span class="badge rounded-pill text-bg-primary px-3 py-2">
                            <?= h(ucwords(str_replace('_', ' ', (string)($user['role_slug'] ?? ec_role())))) ?>
                        </span>

                        <hr class="my-4">

                        <div class="text-start small">
                            <div class="d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">Branch</span>
                                <span class="fw-semibold"><?= h($branchName ?: '—') ?></span>
                            </div>
                            <div class="d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">Status</span>
                                <span class="fw-semibold">
                                    <?php if ((int)($user['active'] ?? 1) === 1): ?>
                                        <span class="badge text-bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge text-bg-secondary">Inactive</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php if ($hasCreatedAt): ?>
                                <div class="d-flex justify-content-between py-2 border-bottom">
                                    <span class="text-muted">Created</span>
                                    <span class="fw-semibold"><?= h($user['created_at'] ?? '—') ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if ($hasLastLogin): ?>
                                <div class="d-flex justify-content-between py-2">
                                    <span class="text-muted">Last Login</span>
                                    <span class="fw-semibold"><?= h($user['last_login'] ?? '—') ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-8">
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-header bg-white border-0 p-4 pb-2">
                        <h5 class="mb-1 fw-bold">Account Details</h5>
                        <div class="text-muted small">Update your name, email and avatar URL.</div>
                    </div>

                    <div class="card-body p-4">
                        <form method="post" autocomplete="off">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Name</label>
                                    <input type="text" name="name" class="form-control rounded-3"
                                           value="<?= h($user['name'] ?? '') ?>" required>
                                </div>

                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Email</label>
                                    <input type="email" name="email" class="form-control rounded-3"
                                           value="<?= h($user['email'] ?? '') ?>" required>
                                </div>

                                <?php if ($hasUsername): ?>
                                    <div class="col-md-6">
                                        <label class="form-label fw-semibold">Username</label>
                                        <input type="text" name="username" class="form-control rounded-3"
                                               value="<?= h($user['username'] ?? '') ?>">
                                    </div>
                                <?php endif; ?>

                                <div class="col-md-6">
                                    <label class="form-label fw-semibold">Role</label>
                                    <input type="text" class="form-control rounded-3"
                                           value="<?= h(ucwords(str_replace('_', ' ', (string)($user['role_slug'] ?? ec_role())))) ?>"
                                           readonly>
                                </div>

                                <?php if ($hasAvatar): ?>
                                    <div class="col-12">
                                        <label class="form-label fw-semibold">Avatar URL</label>
                                        <input type="text" name="avatar_url" class="form-control rounded-3"
                                               value="<?= h($user['avatar_url'] ?? '') ?>"
                                               placeholder="/edenrms/assets/img/avatar-default.jpg">
                                        <div class="form-text">Optional. Use a valid image URL/path.</div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="d-flex justify-content-end gap-2 mt-4">
                                <a href="dashboard.php" class="btn btn-light border rounded-pill px-4">Cancel</a>
                                <button type="submit" class="btn btn-primary rounded-pill px-4">
                                    <i class="bi bi-check2-circle me-1"></i> Save Changes
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card border-0 shadow-sm rounded-4 mt-4">
                    <div class="card-body p-4 d-flex flex-wrap justify-content-between align-items-center gap-3">
                        <div>
                            <h6 class="fw-bold mb-1">Password Security</h6>
                            <div class="text-muted small">Change your password regularly to keep your RMS account secure.</div>
                        </div>
                        <a href="change_password.php" class="btn btn-outline-dark rounded-pill px-4">
                            <i class="bi bi-key me-1"></i> Change Password
                        </a>
                    </div>
                </div>
            </div>
        </div>

    </div>
</main>
</div>
</body>
</html>