<?php
// nyaya-guru/client/profile.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
requireUserLogin();

$db   = getDB();
$uid  = $_SESSION['user_id'];
$user = getCurrentUser();

$states = $db->query("SELECT * FROM states WHERE status=1 ORDER BY name")->fetchAll();

// Load cities for current state
$myCities = [];
if ($user['state_id']) {
    $cs = $db->prepare("SELECT * FROM cities WHERE state_id=? AND status=1 ORDER BY name");
    $cs->execute([$user['state_id']]);
    $myCities = $cs->fetchAll();
}

$success = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRF($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $name     = sanitize($_POST['name'] ?? '');
        $mobile   = sanitize($_POST['mobile'] ?? '');
        $address  = sanitize($_POST['address'] ?? '');
        $stateId  = (int)($_POST['state_id'] ?? 0);
        $cityId   = (int)($_POST['city_id']  ?? 0);
        $newPwd   = $_POST['new_password'] ?? '';
        $confPwd  = $_POST['confirm_password'] ?? '';

        if (!$name) { $error = 'Name is required.'; }
        else {
            $photoPath = $user['profile_photo'];

            // Handle photo upload
            if (!empty($_FILES['profile_photo']['name'])) {
                $file = $_FILES['profile_photo'];
                $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                    $error = 'Invalid image format.';
                } elseif ($file['size'] > 5 * 1024 * 1024) {
                    $error = 'Image too large. Max 5MB.';
                } else {
                    $dir = __DIR__ . '/../assets/uploads/users/';
                    if (!is_dir($dir)) mkdir($dir, 0755, true);
                    $fname = time() . '_' . $uid . '.' . $ext;
                    if (move_uploaded_file($file['tmp_name'], $dir . $fname)) {
                        $photoPath = $fname;
                    } else {
                        $error = 'Upload failed.';
                    }
                }
            }

            if (!$error) {
                // Password change
                if ($newPwd) {
                    if (strlen($newPwd) < 6) {
                        $error = 'Password must be at least 6 characters.';
                    } elseif ($newPwd !== $confPwd) {
                        $error = 'Passwords do not match.';
                    } else {
                        $hashed = hashPassword($newPwd);
                        $db->prepare("UPDATE users SET name=?,mobile=?,address=?,state_id=?,city_id=?,profile_photo=?,password=?,updated_at=NOW() WHERE id=?")
                           ->execute([$name,$mobile,$address,$stateId,$cityId,$photoPath,$hashed,$uid]);
                    }
                } else {
                    $db->prepare("UPDATE users SET name=?,mobile=?,address=?,state_id=?,city_id=?,profile_photo=?,updated_at=NOW() WHERE id=?")
                       ->execute([$name,$mobile,$address,$stateId,$cityId,$photoPath,$uid]);
                }

                if (!$error) {
                    $_SESSION['user_name'] = $name;
                    $success = 'Profile updated successfully!';
                    // Reload user
                    $us = $db->prepare("SELECT * FROM users WHERE id=?");
                    $us->execute([$uid]);
                    $user = $us->fetch();
                    // Reload cities
                    if ($user['state_id']) {
                        $cs->execute([$user['state_id']]);
                        $myCities = $cs->fetchAll();
                    }
                }
            }
        }
    }
}

// Appointment count for sidebar
$apptCount = $db->prepare("SELECT COUNT(*) FROM appointments WHERE user_id=?");
$apptCount->execute([$uid]);
$apptCount = (int)$apptCount->fetchColumn();

$photoUrl = $user['profile_photo'] ? '/nyaya-guru/assets/uploads/users/' . $user['profile_photo'] : null;
$initials = strtoupper(substr($user['name'], 0, 1));

$pageTitle = 'My Profile — Nyaya Guru';
require_once __DIR__ . '/../includes/header.php';
?>

<style>
.profile-page-wrap { background: var(--off-white); min-height: 80vh; padding: 40px 0; }
.profile-card { background: white; border-radius: 16px; box-shadow: var(--shadow); border: 1px solid var(--border); }
.profile-sidebar { background: white; border-radius: 16px; box-shadow: var(--shadow); border: 1px solid var(--border); overflow: hidden; }
.sidebar-header { background: linear-gradient(135deg, var(--primary), #1a3a6b); padding: 28px; text-align: center; }
.photo-ring { width: 90px; height: 90px; border-radius: 50%; border: 3px solid var(--gold); overflow: hidden; display: flex; align-items: center; justify-content: center; background: rgba(212,175,55,.15); margin: 0 auto 14px; cursor: pointer; position: relative; }
.photo-ring img { width: 100%; height: 100%; object-fit: cover; }
.photo-overlay { position: absolute; inset: 0; background: rgba(0,0,0,.45); display: none; align-items: center; justify-content: center; color: white; font-size: .75rem; flex-direction: column; gap: 4px; border-radius: 50%; }
.photo-ring:hover .photo-overlay { display: flex; }
.sec-card { background: white; border-radius: 14px; padding: 24px; box-shadow: var(--shadow); border: 1px solid var(--border); margin-bottom: 20px; }
.sec-title { font-size: .85rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: .05em; padding-bottom: 12px; border-bottom: 2px solid var(--gold); margin-bottom: 18px; display: flex; align-items: center; gap: 8px; }
.sec-title i { color: var(--gold); }
.nav-tab { display: flex; align-items: center; gap: 10px; padding: 10px 16px; border-radius: 8px; font-size: .85rem; font-weight: 600; color: var(--text-light); text-decoration: none; transition: all .25s; }
.nav-tab:hover, .nav-tab.active { background: rgba(10,35,66,.06); color: var(--primary); }
.nav-tab i { width: 16px; text-align: center; color: var(--gold); }
</style>

<!-- Page top bar -->
<div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);padding:28px 0;">
    <div class="container">
        <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
            <div>
                <div style="font-size:.78rem;color:rgba(255,255,255,.5);margin-bottom:3px;">My Account</div>
                <h2 style="color:white;font-size:1.4rem;margin:0;">My Profile</h2>
            </div>
            <div class="d-flex gap-2">
              <a href="<?= SITE_URL ?>/client/dashboard.php" style="background:rgba(255,255,255,.1);color:white;padding:9px 18px;border-radius:10px;font-size:.83rem;font-weight:600;text-decoration:none;border:1px solid rgba(255,255,255,.2);">
    <i class="fas fa-tachometer-alt me-1"></i>Dashboard
</a>

<a href="<?= SITE_URL ?>/logout.php" style="background:rgba(220,53,69,.15);color:#ff8080;padding:9px 14px;border-radius:10px;font-size:.83rem;font-weight:600;text-decoration:none;border:1px solid rgba(220,53,69,.25);">
    <i class="fas fa-sign-out-alt"></i>
</a>
            </div>
        </div>
    </div>
</div>

<div class="profile-page-wrap">
<div class="container">

<?php if ($success): ?>
<div style="background:rgba(40,167,69,.08);border:1px solid rgba(40,167,69,.3);border-radius:12px;padding:14px 18px;margin-bottom:22px;color:#1a7a34;font-size:.88rem;">
    <i class="fas fa-check-circle me-2"></i><?= $success ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div style="background:rgba(220,53,69,.07);border:1px solid rgba(220,53,69,.25);border-radius:12px;padding:14px 18px;margin-bottom:22px;color:#c0392b;font-size:.88rem;">
    <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
</div>
<?php endif; ?>

<div class="row g-4">

    <!-- Sidebar -->
    <div class="col-lg-3">
        <div class="profile-sidebar">
            <div class="sidebar-header">
                <!-- Photo -->
                <div class="photo-ring" onclick="document.getElementById('photoInput').click()">
                    <?php if ($photoUrl): ?>
                        <img src="<?= $photoUrl ?>?t=<?= time() ?>" alt="Photo" id="photoPreview">
                    <?php else: ?>
                        <span id="photoInitials" style="font-size:2rem;font-weight:800;color:var(--gold);font-family:var(--font-heading);"><?= $initials ?></span>
                    <?php endif; ?>
                    <div class="photo-overlay"><i class="fas fa-camera"></i><span>Change</span></div>
                </div>
                <div style="color:white;font-weight:700;font-size:1rem;"><?= htmlspecialchars($user['name']) ?></div>
                <div style="color:rgba(255,255,255,.55);font-size:.78rem;margin-top:3px;"><?= $user['email'] ?></div>
                <div style="margin-top:10px;">
                    <span style="background:rgba(40,167,69,.2);color:#7bffac;padding:4px 14px;border-radius:50px;font-size:.72rem;font-weight:700;">
                        <i class="fas fa-circle me-1" style="font-size:.4rem;"></i>Active Client
                    </span>
                </div>
            </div>
           <div style="padding:16px;">

    <a href="<?= SITE_URL ?>/client/dashboard.php" class="nav-tab">
        <i class="fas fa-tachometer-alt"></i>Dashboard
    </a>

    <a href="<?= SITE_URL ?>/client/profile.php" class="nav-tab active">
        <i class="fas fa-user-edit"></i>Edit Profile
    </a>

    <a href="<?= SITE_URL ?>/lawyers.php" class="nav-tab">
        <i class="fas fa-search"></i>Find Lawyers
    </a>

    <a href="<?= SITE_URL ?>/pages/faq.php" class="nav-tab">
        <i class="fas fa-question-circle"></i>Help & FAQ
    </a>

    <div style="border-top:1px solid var(--border);margin:10px 0;"></div>

    <a href="<?= SITE_URL ?>/logout.php" class="nav-tab" style="color:#dc3545;">
        <i class="fas fa-sign-out-alt" style="color:#dc3545;"></i>Logout
    </a>

</div>
            <!-- Mini stats -->
            <div style="border-top:1px solid var(--border);padding:16px;">
                <div style="display:flex;justify-content:space-between;padding:8px 0;font-size:.82rem;">
                    <span style="color:var(--text-light);">Consultations</span>
                    <span style="font-weight:700;color:var(--primary);"><?= $apptCount ?></span>
                </div>
                <div style="display:flex;justify-content:space-between;padding:8px 0;font-size:.82rem;border-top:1px solid var(--border);">
                    <span style="color:var(--text-light);">Member Since</span>
                    <span style="font-weight:700;color:var(--primary);"><?= date('M Y', strtotime($user['created_at'])) ?></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Main form -->
    <div class="col-lg-9">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= generateCSRF() ?>">
            <input type="file" id="photoInput" name="profile_photo" accept="image/*" style="display:none;" onchange="previewPhoto(this)">

            <!-- Personal Info -->
            <div class="sec-card">
                <h6 class="sec-title"><i class="fas fa-user"></i>Personal Information</h6>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Full Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($user['name']) ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Email Address</label>
                        <input type="email" class="form-control" value="<?= htmlspecialchars($user['email']) ?>" disabled style="background:var(--off-white);">
                        <div class="form-text">Email cannot be changed.</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Mobile Number</label>
                        <input type="tel" name="mobile" class="form-control" value="<?= htmlspecialchars($user['mobile']) ?>" maxlength="10">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Profile Photo</label>
                        <div style="display:flex;align-items:center;gap:12px;">
                            <div class="photo-ring" style="width:52px;height:52px;" onclick="document.getElementById('photoInput').click()">
                                <?php if ($photoUrl): ?>
                                    <img src="<?= $photoUrl ?>" alt="Photo">
                                <?php else: ?>
                                    <span style="font-size:1.2rem;font-weight:800;color:var(--gold);"><?= $initials ?></span>
                                <?php endif; ?>
                                <div class="photo-overlay" style="border-radius:50%;"><i class="fas fa-camera" style="font-size:.7rem;"></i></div>
                            </div>
                            <span style="font-size:.78rem;color:var(--text-light);">Click to change photo<br>JPG, PNG — Max 5MB</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Address -->
            <div class="sec-card">
                <h6 class="sec-title"><i class="fas fa-map-marker-alt"></i>Location & Address</h6>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">State</label>
                        <select name="state_id" id="state_id" class="form-select">
                            <option value="">-- Select State --</option>
                            <?php foreach ($states as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= $user['state_id'] == $s['id'] ? 'selected' : '' ?>><?= $s['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">City</label>
                        <select name="city_id" id="city_id" class="form-select">
                            <option value="">-- Select City --</option>
                            <?php foreach ($myCities as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= $user['city_id'] == $c['id'] ? 'selected' : '' ?>><?= $c['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Full Address</label>
                        <textarea name="address" class="form-control" rows="2" placeholder="Your address"><?= htmlspecialchars($user['address'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Change Password -->
            <div class="sec-card">
                <h6 class="sec-title"><i class="fas fa-lock"></i>Change Password <span style="font-size:.72rem;font-weight:500;color:var(--text-light);text-transform:none;">(leave blank to keep current)</span></h6>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">New Password</label>
                        <div style="position:relative;">
                            <input type="password" name="new_password" id="newPwd" class="form-control" placeholder="Min 6 characters" style="padding-right:44px;">
                            <button type="button" onclick="togglePwd('newPwd',this)" style="position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--text-light);cursor:pointer;padding:0;"><i class="fas fa-eye"></i></button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" name="confirm_password" class="form-control" placeholder="Repeat new password">
                    </div>
                </div>
            </div>

            <div class="d-flex gap-3 justify-content-end">
                <a href="<?= SITE_URL ?>/client/dashboard.php" class="btn btn-outline-secondary px-4" style="border-radius:10px;">Cancel</a>
                <button type="submit" class="btn btn-gold px-5 py-3" style="font-weight:700;border-radius:12px;font-size:.95rem;">
                    <i class="fas fa-save me-2"></i>Save Changes
                </button>
            </div>
        </form>
    </div>

</div>
</div>
</div>

<script>
function previewPhoto(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            // Update all photo rings
            document.querySelectorAll('.photo-ring').forEach(function(ring) {
                var img = ring.querySelector('img');
                var initials = ring.querySelector('#photoInitials, span');
                if (!img) {
                    img = document.createElement('img');
                    img.style.cssText = 'width:100%;height:100%;object-fit:cover;';
                    ring.insertBefore(img, ring.querySelector('.photo-overlay'));
                }
                img.src = e.target.result;
                img.style.display = 'block';
                if (initials && initials !== img) initials.style.display = 'none';
            });
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function togglePwd(id, btn) {
    var inp = document.getElementById(id);
    var show = inp.type === 'password';
    inp.type = show ? 'text' : 'password';
    btn.innerHTML = show ? '<i class="fas fa-eye-slash"></i>' : '<i class="fas fa-eye"></i>';
}
// State → City AJAX
document.getElementById('state_id').addEventListener('change', function() {
    var sid = this.value, sel = document.getElementById('city_id');
    sel.innerHTML = '<option value="">Loading...</option>';
    if (!sid) { sel.innerHTML = '<option value="">-- Select City --</option>'; return; }
  fetch('<?= SITE_URL ?>/api/get_cities.php?state_id=' + sid)
        .then(r => r.json()).then(res => {
            sel.innerHTML = '<option value="">-- Select City --</option>';
            if (res.success) res.data.forEach(c => sel.innerHTML += '<option value="'+c.id+'">'+c.name+'</option>');
        });
});
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>