<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';

// Ensure user is logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$success_msg = '';
$error_msg = '';
if (isset($_SESSION['flash_success'])) {
    $success_msg = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (isset($_SESSION['flash_error'])) {
    $error_msg = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

$upload_dir = 'uploads/profiles/';
if (!is_dir($upload_dir)) {
    @mkdir($upload_dir, 0777, true);
}

// ---- KYC module ----
require_once __DIR__ . '/includes/kyc.php';
kyc_ensure_schema($db);
kyc_handle_post($db, $user_id, 'uploads/kyc/', 'profile.php#kyc');
$kyc_data = kyc_get_data($db, $user_id);

// Sidebar service categories + nested sub-categories
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

// Fetch user data
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

// ---- ID card + seller certificate ----
require_once __DIR__ . '/includes/credentials.php';
cred_ensure_schema($db);
$my_cert = $user ? cred_get_certificate($db, $user, true) : null;

// Handle Profile Pic Upload
if (isset($_POST['upload_pic']) && isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {
    $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
    $filename = $_FILES['profile_pic']['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (in_array($ext, $allowed_types) && $_FILES['profile_pic']['size'] <= 2097152) {
        $new_name = 'user_' . $user_id . '_' . time() . '.' . $ext;
        $destination = $upload_dir . $new_name;
        
        if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $destination)) {
            $old_pic = $user['profile_pic'];
            $db->insert("UPDATE users SET profile_pic = ? WHERE id = ?", [$new_name, $user_id]);
            if ($old_pic && file_exists($upload_dir . $old_pic)) {
                @unlink($upload_dir . $old_pic);
            }
            $_SESSION['flash_success'] = $lang->translate('pic_updated', 'Profile picture updated successfully!');
        } else {
            $_SESSION['flash_error'] = $lang->translate('pic_upload_failed', 'Failed to upload picture.');
        }
    } else {
        $_SESSION['flash_error'] = $lang->translate('invalid_pic', 'Only JPG, PNG, GIF under 2MB are allowed.');
    }
    redirect('profile.php#edit');
}

// Handle Profile Pic Remove
if (isset($_POST['remove_pic'])) {
    $old_pic = $user['profile_pic'];
    if ($old_pic && file_exists($upload_dir . $old_pic)) {
        @unlink($upload_dir . $old_pic);
    }
    $db->insert("UPDATE users SET profile_pic = NULL WHERE id = ?", [$user_id]);
    $_SESSION['flash_success'] = $lang->translate('pic_removed', 'Profile picture removed successfully!');
    redirect('profile.php#edit');
}

// Handle Basic Profile Update
if (isset($_POST['update_profile'])) {
    $name = sanitize($_POST['name']);
    $email = sanitize($_POST['email']);
    $gender = sanitize($_POST['gender']);
    
    if (empty($name) || empty($email) || empty($gender)) {
        $_SESSION['flash_error'] = $lang->translate('fill_all_fields', 'Please fill all fields.');
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['flash_error'] = $lang->translate('valid_email', 'Valid email required.');
    } else {
        $db->insert("UPDATE users SET name = ?, email = ?, gender = ? WHERE id = ?", [$name, $email, $gender, $user_id]);
        $_SESSION['user_name'] = $name; 
        $_SESSION['flash_success'] = $lang->translate('profile_updated', 'Profile updated successfully!');
    }
    redirect('profile.php#edit');
}

// Handle Password Change
if (isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $_SESSION['flash_error'] = $lang->translate('fill_all_fields', 'Please fill all fields.');
    } elseif ($new_password !== $confirm_password) {
        $_SESSION['flash_error'] = $lang->translate('password_mismatch', 'Passwords do not match!');
    } elseif (!password_verify($current_password, $user['password'])) {
        $_SESSION['flash_error'] = $lang->translate('wrong_current_password', 'Wrong current password!');
    } else {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $db->insert("UPDATE users SET password = ? WHERE id = ?", [$hashed_password, $user_id]);
        $_SESSION['flash_success'] = $lang->translate('password_changed', 'Password changed successfully!');
    }
    redirect('profile.php#password');
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';

$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

/* ---- Subscription + KYC summary shown on the "My Profile" card ---- */
$is_subscribed_user = !empty($user['is_subscribed']);
$subscription_till  = '';
if ($is_subscribed_user) {
    foreach (['subscription_expiry', 'subscription_end', 'subscribed_till', 'subscription_date'] as $__c) {
        if (!empty($user[$__c])) { $subscription_till = date('d M Y', strtotime($user[$__c])); break; }
    }
}
$__kyc_prog = kyc_progress($db, $user_id, $user['user_type'] ?? 'customer');
switch ($__kyc_prog['status']) {
    case 'approved': $__kyc_txt = 'Approved';            $__kyc_css = 'text-emerald-600'; break;
    case 'pending':  $__kyc_txt = 'Pending verification'; $__kyc_css = 'text-amber-600';  break;
    case 'rejected': $__kyc_txt = 'Rejected — please update'; $__kyc_css = 'text-rose-600'; break;
    default:         $__kyc_txt = 'Not submitted';        $__kyc_css = 'text-slate-500';
}
$__kyc_txt .= ' (' . $__kyc_prog['percent'] . '%)';

// Ensure correct dashboard link
$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lang->translate('my_profile', 'My Profile'); ?> - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [1=>[],5=>[]]; foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'My Profile',
    'active' => 'profile',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : 'assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => 'currentTab: (window.location.hash ? window.location.hash.substring(1) : \'profile\')',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">
                
                <?php if ($success_msg): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-check-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>

                <?php if ($error_msg): ?>
                <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>

                <div class="max-w-4xl mx-auto pb-20">

                    <div x-show="currentTab === 'profile'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="h-32 bg-gradient-to-r from-indigo-500 to-purple-600"></div>
                            <div class="px-6 py-6 sm:px-10 pb-10 relative">
                                <div class="absolute -top-16 left-6 sm:left-10">
                                    <div class="w-32 h-32 rounded-full border-4 border-white shadow-lg overflow-hidden bg-white">
                                        <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                            <img src="<?php echo $profile_image_url; ?>" class="w-full h-full object-cover">
                                        <?php else: ?>
                                            <div class="w-full h-full bg-indigo-100 text-indigo-700 flex items-center justify-center text-4xl font-bold">
                                                <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="h-6"></div>

                                <h2 class="text-3xl font-extrabold text-gray-900"><?php echo htmlspecialchars($user['name']); ?></h2>

                                <div class="flex flex-wrap items-center gap-2 mt-2 mb-6">
                                    <span class="inline-flex items-center gap-1.5 text-[11px] font-black uppercase tracking-wider px-2.5 py-1 rounded-full bg-indigo-50 text-indigo-600 border border-indigo-100">
                                        <i class="fas fa-user-check"></i> <?php echo htmlspecialchars(cred_role_label($db, $user)); ?>
                                    </span>
                                    <?php if ($is_subscribed_user): ?>
                                        <span class="inline-flex items-center gap-1.5 text-[11px] font-black uppercase tracking-wider px-2.5 py-1 rounded-full bg-amber-50 text-amber-700 border border-amber-200">
                                            <i class="fas fa-crown"></i> Subscription Active<?php echo $subscription_till ? ' · till ' . htmlspecialchars($subscription_till) : ''; ?>
                                        </span>
                                    <?php else: ?>
                                        <a href="subscription.php" class="inline-flex items-center gap-1.5 text-[11px] font-black uppercase tracking-wider px-2.5 py-1 rounded-full bg-slate-100 text-slate-500 border border-slate-200 hover:bg-slate-200">
                                            <i class="fas fa-lock"></i> No Subscription · Subscribe
                                        </a>
                                    <?php endif; ?>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-2 gap-y-6 gap-x-10 border-t border-gray-100 pt-6">
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">User ID</p>
                                        <p class="font-semibold text-gray-800"><i class="fas fa-hashtag text-gray-400 mr-2"></i> <?php echo (int)$user['id']; ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Member ID</p>
                                        <p class="font-semibold text-indigo-600"><i class="fas fa-id-badge text-gray-400 mr-2"></i> <?php echo htmlspecialchars(cred_member_id($user_id)); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Mobile Number</p>
                                        <p class="font-semibold text-gray-800"><i class="fas fa-phone-alt text-gray-400 mr-2"></i> <?php echo htmlspecialchars($user['mobile']); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Email Address</p>
                                        <p class="font-semibold text-gray-800"><i class="fas fa-envelope text-gray-400 mr-2"></i> <?php echo htmlspecialchars($user['email']); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Gender</p>
                                        <p class="font-semibold text-gray-800"><i class="fas fa-venus-mars text-gray-400 mr-2"></i> <?php echo ucfirst($user['gender']); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Member Since</p>
                                        <p class="font-semibold text-gray-800"><i class="fas fa-calendar-alt text-gray-400 mr-2"></i> <?php echo date('F d, Y', strtotime($user['created_at'])); ?></p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Subscription Status</p>
                                        <p class="font-semibold <?php echo $is_subscribed_user ? 'text-emerald-600' : 'text-gray-500'; ?>">
                                            <i class="fas fa-crown text-gray-400 mr-2"></i>
                                            <?php echo $is_subscribed_user ? 'Active' . ($subscription_till ? ' (till ' . htmlspecialchars($subscription_till) . ')' : '') : 'Not subscribed'; ?>
                                        </p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">KYC Status</p>
                                        <p class="font-semibold <?php echo $__kyc_css; ?>"><i class="fas fa-id-card text-gray-400 mr-2"></i> <?php echo htmlspecialchars($__kyc_txt); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'edit'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-user-edit text-indigo-600 mr-2"></i> Edit Personal Profile</h3>
                            </div>
                            <div class="p-6 md:p-8 flex flex-col md:flex-row gap-8">
                                
                                <div class="w-full md:w-1/3 flex flex-col items-center">
                                    <div class="relative w-32 h-32 mb-4" id="profileImageContainer">
                                        <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                            <img src="<?php echo $profile_image_url; ?>" alt="Profile" class="w-full h-full rounded-full object-cover border-4 border-indigo-50 shadow-md">
                                        <?php else: ?>
                                            <div class="w-full h-full rounded-full bg-gradient-to-tr from-indigo-500 to-cyan-600 flex items-center justify-center text-4xl font-bold text-white shadow-md border-4 border-indigo-50">
                                                <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <form method="POST" enctype="multipart/form-data" class="flex flex-col w-full space-y-2">
                                        <label class="w-full cursor-pointer bg-gray-50 hover:bg-gray-100 text-gray-700 font-medium py-2 px-4 rounded-lg text-sm text-center transition-colors border border-gray-200">
                                            <i class="fas fa-camera mr-1"></i> Choose File
                                            <input type="file" name="profile_pic" class="hidden" accept="image/jpeg, image/png, image/gif" onchange="previewImage(event)">
                                        </label>
                                        <button type="submit" name="upload_pic" id="uploadBtn" class="hidden w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-sm text-sm">
                                            Save Picture
                                        </button>
                                    </form>
                                    <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                    <form method="POST" class="w-full mt-2">
                                        <button type="submit" name="remove_pic" onclick="return confirm('<?php echo $lang->translate('confirm_remove_pic', 'Are you sure you want to remove the picture?'); ?>');" class="w-full bg-white hover:bg-rose-50 text-rose-500 font-medium py-2 px-4 rounded-lg text-sm transition-colors border border-rose-100">
                                            <i class="fas fa-trash-alt mr-1"></i> Remove
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </div>

                                <div class="w-full md:w-2/3">
                                    <form method="POST" class="space-y-5">
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1">Full Name <span class="text-rose-500">*</span></label>
                                            <input type="text" name="name" value="<?php echo htmlspecialchars($user['name']); ?>" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1">Mobile Number <span class="text-xs text-rose-500 font-normal">(Cannot be changed here)</span></label>
                                            <input type="text" value="<?php echo htmlspecialchars($user['mobile']); ?>" disabled class="w-full px-4 py-2.5 bg-gray-100 border border-gray-200 rounded-xl text-gray-500 cursor-not-allowed">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1">Email Address <span class="text-rose-500">*</span></label>
                                            <input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1">Gender <span class="text-rose-500">*</span></label>
                                            <select name="gender" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all">
                                                <option value="male" <?php echo ($user['gender'] == 'male') ? 'selected' : ''; ?>>Male</option>
                                                <option value="female" <?php echo ($user['gender'] == 'female') ? 'selected' : ''; ?>>Female</option>
                                                <option value="other" <?php echo ($user['gender'] == 'other') ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        <div class="pt-4">
                                            <button type="submit" name="update_profile" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-8 rounded-xl shadow-md transition-colors w-full sm:w-auto">
                                                <i class="fas fa-save mr-2"></i> Save Profile
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'kyc'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-id-card text-blue-600 mr-2"></i> KYC Verification</h3>
                            </div>
                            <div class="p-6 md:p-8">
                                <?php echo kyc_render_form($kyc_data, '', $user['user_type'] ?? 'customer'); ?>
                            </div>
                        </div>
                    </div>

                    <div x-show="currentTab === 'password'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-lock text-rose-500 mr-2"></i> <?php echo $lang->translate('change_password', 'Change Password'); ?></h3>
                            </div>
                            <div class="p-6 md:p-8">
                                <form method="POST">
                                    <div class="space-y-6 max-w-md">
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1"><?php echo $lang->translate('current_password', 'Current Password'); ?> <span class="text-rose-500">*</span></label>
                                            <input type="password" name="current_password" required class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-rose-500 transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1"><?php echo $lang->translate('new_password', 'New Password'); ?> <span class="text-rose-500">*</span></label>
                                            <input type="password" name="new_password" required class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-rose-500 transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-bold text-gray-700 mb-1"><?php echo $lang->translate('confirm_new_password', 'Confirm New Password'); ?> <span class="text-rose-500">*</span></label>
                                            <input type="password" name="confirm_password" required class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-rose-500 transition-all">
                                        </div>
                                    </div>
                                    <div class="mt-8 pt-6 border-t border-gray-100">
                                        <button type="submit" name="change_password" class="bg-gray-800 hover:bg-gray-900 text-white font-bold py-3 px-8 rounded-xl shadow-md transition-colors w-full sm:w-auto">
                                            <i class="fas fa-key mr-2"></i> <?php echo $lang->translate('update_password', 'Update Password'); ?>
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- ================= ID CARD ================= -->
                    <div x-show="currentTab === 'id_card'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50 flex flex-wrap items-center justify-between gap-2">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-id-badge text-indigo-600 mr-2"></i> My Member ID Card</h3>
                                <span class="text-[11px] font-bold px-3 py-1 rounded-full bg-indigo-50 text-indigo-600 border border-indigo-100">
                                    <?php echo htmlspecialchars(cred_member_id($user_id)); ?>
                                </span>
                            </div>
                            <div class="p-6 md:p-10 bg-slate-50/60">
                                <?php echo cred_render_id_card($db, $user, ['rel' => '', 'brand' => $company_name, 'logo' => $company_logo]); ?>
                                <p class="text-center text-xs text-slate-500 mt-6 max-w-md mx-auto leading-relaxed">
                                    Your card has a <b>front</b> and a <b>back</b> — card number, employee ID, photo and validity on the
                                    front; QR verification, signature panel, barcode and terms on the back.
                                    <b>Download PDF</b> gives you both faces as a ready-to-print 2-page file at the standard
                                    ID-card size (54 × 85.6 mm) — the QR code links back to your account for verification.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- ================= CERTIFICATE ================= -->
                    <div x-show="currentTab === 'certificate'" style="display:none;" x-transition.opacity>
                        <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50 flex flex-wrap items-center justify-between gap-2">
                                <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-certificate text-yellow-500 mr-2"></i> Seller Certificate</h3>
                                <?php if ($my_cert): ?>
                                    <span class="text-[11px] font-bold px-3 py-1 rounded-full bg-amber-50 text-amber-700 border border-amber-100">
                                        <?php echo htmlspecialchars($my_cert['cert_no']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>

                            <?php if ($my_cert): ?>
                                <div class="p-5 md:p-8 bg-slate-50/60">
                                    <?php echo cred_render_certificate($db, $user, $my_cert, ['rel' => '', 'brand' => $company_name, 'logo' => $company_logo]); ?>
                                    <p class="text-center text-xs text-slate-500 mt-6 max-w-lg mx-auto leading-relaxed">
                                        Issued on <b><?php echo date('d M Y', strtotime($my_cert['issued_on'])); ?></b>
                                        <?php if (!empty($my_cert['valid_till'])): ?> • valid till <b><?php echo date('d M Y', strtotime($my_cert['valid_till'])); ?></b><?php endif; ?>.
                                        Download it as a high-resolution PNG, or use Print → “Save as PDF” for a printable copy.
                                    </p>
                                </div>
                            <?php else: ?>
                                <div class="p-16 text-center text-gray-500">
                                    <div class="w-20 h-20 bg-yellow-50 rounded-full flex items-center justify-center mx-auto mb-5 text-yellow-600 text-3xl border border-yellow-100">
                                        <i class="fas fa-award"></i>
                                    </div>
                                    <h3 class="text-2xl font-extrabold text-gray-800 mb-2">For Sellers Only</h3>
                                    <p class="text-gray-500 max-w-sm mx-auto mb-6">Your official partnership certificate is generated automatically the moment your seller account is approved.</p>
                                    <a href="upgrade_request.php" class="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm shadow-lg transition-colors">
                                        <i class="fas fa-store"></i> Become a Seller
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
                <?php echo cred_assets(''); ?>
            </main>
        </div>
    </div>

    <script>
    function previewImage(event) {
        if(event.target.files.length > 0) {
            var src = URL.createObjectURL(event.target.files[0]);
            var container = document.getElementById('profileImageContainer');
            container.innerHTML = '<img src="' + src + '" class="w-full h-full rounded-full object-cover border-4 border-indigo-50 shadow-md">';
            document.getElementById('uploadBtn').classList.remove('hidden');
        }
    }
    </script>
</body>
</html>