<?php
require_once __DIR__ . '/../../includes/init.php';
middleware();

$db  = getDBConnection();
$uid = (int)getSession('user_id');
$user = dbRow($db, "SELECT * FROM users WHERE id=?", [$uid]);

$success = '';
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $fullName = trim($_POST['full_name'] ?? '');
        $phone    = trim($_POST['phone'] ?? '');
        if (!$fullName) {
            $error = 'Full name is required.';
        } else {
            try {
                // Check if phone column exists
                $cols = array_column($db->query("SHOW COLUMNS FROM users")->fetchAll(), 'Field');
                if (in_array('phone', $cols)) {
                    $db->prepare("UPDATE users SET full_name=?, phone=? WHERE id=?")
                       ->execute([$fullName, $phone ?: null, $uid]);
                } else {
                    $db->prepare("UPDATE users SET full_name=? WHERE id=?")
                       ->execute([$fullName, $uid]);
                }
                $_SESSION['full_name'] = $fullName;
                $success = 'Profile updated successfully.';
                $user = dbRow($db, "SELECT * FROM users WHERE id=?", [$uid]);
            } catch (PDOException $e) {
                $error = 'Update failed.';
            }
        }
    }
}

$pageTitle = 'My Profile';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><h1><i class="bi bi-person-circle me-2 text-primary"></i>My Profile</h1></div>
</div>

<?php if ($success): ?>
<div class="alert alert-success d-flex align-items-center gap-2">
    <i class="bi bi-check-circle-fill"></i><?= h($success) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?= h($error) ?></div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-md-4">
        <div class="erp-card text-center">
            <div class="erp-avatar mx-auto mb-3"
                 style="width:72px;height:72px;font-size:2rem;background:var(--erp-primary);">
                <?= strtoupper(substr($user['full_name'], 0, 1)) ?>
            </div>
            <h5 class="fw-bold mb-1"><?= h($user['full_name']) ?></h5>
            <div><?= roleBadge($user['role']) ?></div>
            <div class="text-muted mt-2" style="font-size:.82rem;">
                <i class="bi bi-person me-1"></i><?= h($user['username']) ?>
            </div>
            <?php if (!empty($user['division'])): ?>
            <div class="text-muted" style="font-size:.82rem;">
                <i class="bi bi-diagram-3 me-1"></i><?= h($user['division']) ?>
            </div>
            <?php endif; ?>
            <div class="text-muted mt-1" style="font-size:.75rem;">
                Member since <?= date('M Y', strtotime($user['created_at'])) ?>
            </div>
        </div>
    </div>
    <div class="col-md-8">
        <div class="erp-card">
            <h6 class="fw-bold mb-3">Edit Profile</h6>
            <form method="POST" novalidate>
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                <div class="mb-3">
                    <label class="form-label fw-semibold" style="font-size:.86rem;">Full Name</label>
                    <input type="text" name="full_name" class="form-control"
                           value="<?= h($user['full_name']) ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold" style="font-size:.86rem;">Username</label>
                    <input type="text" class="form-control" value="<?= h($user['username']) ?>" disabled>
                    <div class="form-text">Username cannot be changed.</div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold" style="font-size:.86rem;">Role</label>
                    <input type="text" class="form-control" value="<?= h(roleLabel($user['role'])) ?>" disabled>
                </div>
                <div class="mb-4">
                    <label class="form-label fw-semibold" style="font-size:.86rem;">Phone</label>
                    <input type="tel" name="phone" class="form-control"
                           value="<?= h($user['phone'] ?? '') ?>" placeholder="Mobile number">
                </div>
                <button type="submit" class="btn btn-erp">
                    <i class="bi bi-check-lg me-2"></i>Save Changes
                </button>
            </form>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
