<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-bs5.min.css">

<div class="d-flex align-items-center justify-content-between mb-4">
    <h4 class="page-title mb-0">
        <i class="bi bi-pencil-square me-2 text-primary"></i><?= lang('Admin.edit_user') ?>:
        <span class="text-primary unicode-text"><?= esc($profile['name']) ?></span>
    </h4>
    <div class="d-flex gap-2">
        <a href="<?= site_url('admin/users/view/'.$profile['id']) ?>" class="btn btn-outline-info btn-sm">
            <i class="bi bi-eye me-1"></i><?= lang('Admin.view') ?>
        </a>
        <a href="<?= site_url('admin/users') ?>" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left me-1"></i>Back
        </a>
    </div>
</div>

<form action="<?= site_url('admin/users/update/'.$profile['id']) ?>" method="post"
      enctype="multipart/form-data" novalidate>
    <?= csrf_field() ?>

    <div class="row g-4">
        <!-- Left column -->
        <div class="col-lg-8">
            <!-- Basic Info -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-person me-2"></i>Basic Information</h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.name') ?> <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control unicode-input"
                                   value="<?= esc(old('name', $profile['name'])) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.company_name') ?></label>
                            <input type="text" name="company_name" class="form-control unicode-input"
                                   value="<?= esc(old('company_name', $profile['company_name'])) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.designation') ?></label>
                            <input type="text" name="designation" class="form-control unicode-input"
                                   value="<?= esc(old('designation', $profile['designation'])) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium">
                                <?= lang('Admin.email') ?>
                                <span class="badge bg-success-subtle text-success border border-success-subtle ms-1" style="font-size:.6rem;font-weight:500">🔒 Encrypted</span>
                            </label>
                            <input type="email" name="email" class="form-control"
                                   value="<?= esc(old('email', $profile['email'])) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium">
                                <?= lang('Admin.mobile') ?>
                                <span class="badge bg-success-subtle text-success border border-success-subtle ms-1" style="font-size:.6rem;font-weight:500">🔒 Encrypted</span>
                            </label>
                            <div class="input-group">
                                <?php $selectedCode = old('mobile_country_code', $profile['mobile_country_code'] ?? '+91'); include(APPPATH.'Views/admin/partials/_country_codes.php'); ?>
                                <input type="tel" name="mobile" class="form-control"
                                       value="<?= esc(old('mobile', $profile['mobile'])) ?>"
                                       placeholder="98765 43210">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.status') ?></label>
                            <div class="form-check form-switch mt-2">
                                <input type="checkbox" name="is_active" class="form-check-input" id="isActive"
                                       value="1" <?= old('is_active', $profile['is_active']) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="isActive"><?= lang('Admin.active') ?></label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-medium">
                                <?= lang('Admin.address') ?>
                                <span class="badge bg-success-subtle text-success border border-success-subtle ms-1" style="font-size:.6rem;font-weight:500">🔒 Encrypted</span>
                            </label>
                            <textarea name="address" class="form-control unicode-input" rows="2"><?= esc(old('address', $profile['address'])) ?></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-medium"><?= lang('Admin.about_us') ?></label>
                            <textarea name="about_us" id="aboutUs" class="form-control unicode-input" rows="5"><?= old('about_us', $profile['about_us']) ?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Map Location -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-geo-alt me-2"></i><?= lang('Admin.map_location') ?></h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.latitude') ?></label>
                            <input type="number" name="latitude" class="form-control"
                                   value="<?= esc(old('latitude', $profile['latitude'])) ?>" step="0.00000001">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.longitude') ?></label>
                            <input type="number" name="longitude" class="form-control"
                                   value="<?= esc(old('longitude', $profile['longitude'])) ?>" step="0.00000001">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Social Links -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-share me-2"></i><?= lang('Admin.social_links') ?></h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <?php $socials = ['linkedin'=>'bi-linkedin','instagram'=>'bi-instagram','facebook'=>'bi-facebook','twitter'=>'bi-twitter-x','youtube'=>'bi-youtube']; ?>
                        <?php foreach ($socials as $key => $icon): ?>
                        <div class="col-md-6">
                            <label class="form-label fw-medium"><?= lang('Admin.'.$key) ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi <?= $icon ?>"></i></span>
                                <input type="url" name="<?= $key ?>" class="form-control"
                                       value="<?= esc(old($key, $profile[$key])) ?>">
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Media: Videos -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-play-circle me-2 text-danger"></i>Videos</h6>
                </div>
                <div class="card-body">
                    <?php if (! empty($videos)): ?>
                    <p class="small text-muted fw-semibold mb-2">Existing Videos</p>
                    <div class="list-group mb-3">
                        <?php foreach ($videos as $m): ?>
                        <div class="list-group-item d-flex align-items-center justify-content-between gap-2 py-2">
                            <div class="d-flex align-items-center gap-2 overflow-hidden">
                                <i class="bi bi-play-circle-fill text-danger flex-shrink-0"></i>
                                <span class="small text-truncate">
                                    <?= $m['url']
                                        ? '<a href="'.esc($m['url']).'" target="_blank">'.esc(truncate_text($m['url'],55)).'</a>'
                                        : esc($m['original_name'] ?? basename($m['file_path'])) ?>
                                </span>
                            </div>
                            <form action="<?= site_url('admin/users/delete-media/'.$m['id']) ?>" method="post" class="d-inline flex-shrink-0">
                                <?= csrf_field() ?>
                                <button type="submit" class="btn btn-xs btn-outline-danger" title="Remove"
                                        onclick="return confirm('Remove this video?')">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <label class="form-label small fw-medium">Upload Video Files <span class="text-muted">(MP4, WebM — max 200 MB)</span></label>
                    <input type="file" name="videos[]" class="form-control form-control-sm mb-3" multiple accept="video/*">

                    <label class="form-label small fw-medium">Add Video URLs <span class="text-muted">(YouTube / Vimeo)</span></label>
                    <div id="videoUrlRows"></div>
                    <button type="button" class="btn btn-sm btn-outline-success mt-1"
                            onclick="addVideoUrlRow('')">
                        <i class="bi bi-plus-lg me-1"></i>Add Video URL
                    </button>
                </div>
            </div>

            <!-- Media: Documents -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-file-earmark-text me-2 text-primary"></i>Documents</h6>
                </div>
                <div class="card-body">
                    <?php if (! empty($docs)): ?>
                    <p class="small text-muted fw-semibold mb-2">Existing Documents</p>
                    <div class="list-group mb-3">
                        <?php foreach ($docs as $m): ?>
                        <div class="list-group-item d-flex align-items-center justify-content-between gap-2 py-2">
                            <div class="d-flex align-items-center gap-2 overflow-hidden">
                                <i class="bi bi-file-earmark-pdf-fill text-danger flex-shrink-0"></i>
                                <span class="small text-truncate"><?= esc($m['original_name'] ?? basename($m['file_path'])) ?></span>
                                <?php if ($m['file_size']): ?>
                                <span class="badge bg-light text-muted border flex-shrink-0"><?= human_filesize($m['file_size']) ?></span>
                                <?php endif; ?>
                            </div>
                            <form action="<?= site_url('admin/users/delete-media/'.$m['id']) ?>" method="post" class="d-inline flex-shrink-0">
                                <?= csrf_field() ?>
                                <button type="submit" class="btn btn-xs btn-outline-danger" onclick="return confirm('Remove this document?')">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <label class="form-label small fw-medium">Upload Documents <span class="text-muted">(PDF, DOC, XLS, PPT — max 20 MB)</span></label>
                    <input type="file" name="documents[]" class="form-control form-control-sm" multiple
                           accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt">
                </div>
            </div>

            <!-- Media: Gallery -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-images me-2 text-success"></i>Photo Gallery</h6>
                </div>
                <div class="card-body">
                    <?php if (! empty($gallery)): ?>
                    <p class="small text-muted fw-semibold mb-2">Existing Gallery Images (<?= count($gallery) ?>)</p>
                    <div class="row g-2 mb-3">
                        <?php foreach ($gallery as $img): ?>
                        <div class="col-4 col-sm-3 position-relative">
                            <img src="<?= base_url('uploads/'.esc($img['file_path'])) ?>"
                                 class="img-fluid rounded" loading="lazy"
                                 style="height:80px;width:100%;object-fit:cover;border:1px solid #eee">
                            <form action="<?= site_url('admin/users/delete-media/'.$img['id']) ?>" method="post"
                                  style="position:absolute;top:4px;right:8px">
                                <?= csrf_field() ?>
                                <button type="submit"
                                        class="btn btn-danger btn-xs rounded-circle shadow-sm"
                                        style="width:22px;height:22px;padding:0;font-size:12px;line-height:1"
                                        onclick="return confirm('Remove this image?')" title="Remove">
                                    &times;
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <label class="form-label small fw-medium">Upload Gallery Images <span class="text-muted">(JPG, PNG, WebP — max 5 MB each)</span></label>
                    <input type="file" name="gallery_images[]" id="galleryInput" class="form-control form-control-sm mb-2"
                           multiple accept="image/jpeg,image/jpg,image/png,image/webp,image/gif">
                    <div id="galleryPreview" class="row g-2 mt-1"></div>
                </div>
            </div>
        </div>

        <!-- Right column -->
        <div class="col-lg-4">
            <!-- Profile Photo -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-image me-2"></i><?= lang('Admin.profile_photo') ?></h6>
                </div>
                <div class="card-body text-center">
                    <div class="photo-preview mb-3">
                        <img id="photoPreview" src="<?= profile_photo_url($profile['profile_photo']) ?>"
                             class="rounded-circle shadow" width="120" height="120"
                             style="object-fit:cover" alt="Photo">
                    </div>
                    <input type="file" name="profile_photo" id="profilePhoto"
                           class="form-control form-control-sm"
                           accept="image/jpeg,image/jpg,image/png,image/webp">
                    <div class="form-text">Leave blank to keep current photo.</div>
                </div>
            </div>

            <!-- Company Logo -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h6 class="mb-0 fw-semibold"><i class="bi bi-building me-2"></i>Company Logo</h6>
                </div>
                <div class="card-body text-center">
                    <div class="logo-preview mb-3">
                        <img id="logoPreview"
                             src="<?= company_logo_url($profile['company_logo'] ?? null) ?>"
                             style="width:120px;height:80px;object-fit:contain;
                                    border:1px solid #eee;border-radius:8px;padding:6px;background:#fafafa"
                             alt="Company Logo">
                    </div>
                    <input type="file" name="company_logo" id="companyLogo"
                           class="form-control form-control-sm mb-2"
                           accept="image/jpeg,image/jpg,image/png,image/webp,image/gif,image/svg+xml">
                    <div class="form-text mb-2">JPG, PNG, WebP, SVG — max 5 MB. Leave blank to keep current.</div>
                    <?php if (!empty($profile['company_logo'])): ?>
                    <div class="form-check form-check-sm text-start">
                        <input type="checkbox" name="remove_company_logo" id="removeLogo"
                               class="form-check-input" value="1">
                        <label class="form-check-label small text-danger" for="removeLogo">
                            Remove current logo
                        </label>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Profile Info -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body">
                    <dl class="mb-0">
                        <dt class="small text-muted">Profile Slug</dt>
                        <dd class="small font-monospace text-truncate"><?= esc($profile['slug'] ?? 'auto-generated') ?></dd>
                        <dt class="small text-muted mt-2">Created</dt>
                        <dd class="small"><?= date('d M Y', strtotime($profile['created_at'])) ?></dd>
                    </dl>
                </div>
            </div>

            <!-- Submit -->
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-check-circle me-2"></i><?= lang('Admin.update') ?>
                        </button>
                        <a href="<?= site_url('admin/users') ?>" class="btn btn-outline-secondary">
                            <i class="bi bi-x me-1"></i><?= lang('Admin.cancel') ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<!-- Define global helpers FIRST — before Summernote loads, so onclick="" always works -->
<script>
// ── Video URL rows (global — called by onclick attribute) ───
window.addVideoUrlRow = function (value) {
    var container = document.getElementById('videoUrlRows');
    if (!container) return;
    var row = document.createElement('div');
    row.className = 'd-flex gap-2 mb-2 align-items-center';
    var input = document.createElement('input');
    input.type        = 'url';
    input.name        = 'video_urls[]';
    input.className   = 'form-control form-control-sm';
    input.placeholder = 'https://youtube.com/watch?v=...';
    input.value       = value || '';
    var btn = document.createElement('button');
    btn.type      = 'button';
    btn.className = 'btn btn-sm btn-outline-danger flex-shrink-0';
    btn.title     = 'Remove';
    btn.innerHTML = '<i class="bi bi-x-lg"></i>';
    btn.addEventListener('click', function () { row.remove(); });
    row.appendChild(input);
    row.appendChild(btn);
    container.appendChild(row);
    input.focus();
};
</script>

<script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-bs5.min.js"></script>
<script>
// ── Summernote rich text editor ─────────────────────────────
try {
    $('#aboutUs').summernote({
        height: 200,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold','italic','underline','clear']],
            ['para', ['ul','ol','paragraph']],
            ['insert', ['link']],
            ['view', ['codeview']],
        ],
    });
} catch(e) { /* Summernote unavailable — plain textarea fallback */ }

// ── Photo preview ───────────────────────────────────────────
document.getElementById('profilePhoto').addEventListener('change', function () {
    var file = this.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onload = function(e) { document.getElementById('photoPreview').src = e.target.result; };
        reader.readAsDataURL(file);
    }
});

// ── Company logo preview ────────────────────────────────────
document.getElementById('companyLogo').addEventListener('change', function () {
    var file = this.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onload = function(e) { document.getElementById('logoPreview').src = e.target.result; };
        reader.readAsDataURL(file);
    }
});

// ── Gallery image preview ───────────────────────────────────
document.getElementById('galleryInput').addEventListener('change', function () {
    var preview = document.getElementById('galleryPreview');
    preview.innerHTML = '';
    Array.from(this.files).forEach(function (file) {
        var col = document.createElement('div');
        col.className = 'col-4 col-sm-3';
        var img = document.createElement('img');
        img.className = 'img-fluid rounded';
        img.style.cssText = 'height:80px;width:100%;object-fit:cover;border:1px solid #dee2e6';
        var reader = new FileReader();
        reader.onload = function(e) { img.src = e.target.result; };
        reader.readAsDataURL(file);
        col.appendChild(img);
        preview.appendChild(col);
    });
});
</script>
<?= $this->endSection() ?>
