<?php
// meevakeel/lawyer/profile.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
requireLawyerLogin();

$db     = getDB();
$lid    = $_SESSION['lawyer_id'];
$lawyer = getCurrentLawyer();

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

// Existing expertise
$expStmt = $db->prepare("SELECT category_id FROM lawyer_expertise WHERE lawyer_id=?");
$expStmt->execute([$lid]);
$myExpertise = array_column($expStmt->fetchAll(), 'category_id');

$success = $error = '';

// ── Handle form submit ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRF($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $name    = sanitize($_POST['name'] ?? '');
        $mobile  = sanitize($_POST['mobile'] ?? '');
        $about   = sanitize($_POST['about'] ?? '');
        $langs   = implode(',', (array)($_POST['languages'] ?? []));
        $stateId = (int)($_POST['state_id'] ?? 0);
        $cityId  = (int)($_POST['city_id']  ?? 0);
        $address = sanitize($_POST['address'] ?? '');
        $fee     = ($lawyer['experience_years'] === '2-4') ? 0 : (float)($_POST['consultation_fee'] ?? 0);
        $expertise = (array)($_POST['expertise'] ?? []);

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

            // Handle photo upload
            if (!empty($_FILES['profile_photo']['name'])) {
                $file    = $_FILES['profile_photo'];
                $ext     = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                $allowed = ['jpg','jpeg','png','gif','webp'];
                if (!in_array($ext, $allowed)) {
                    $error = 'Invalid image format. Use JPG, PNG or GIF.';
                } elseif ($file['size'] > MAX_FILE_SIZE) {
                    $error = 'Image too large. Max 5MB.';
                } else {
                    $uploadDir = __DIR__ . '/../assets/uploads/lawyers/';
                    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                    $newName = time() . '_' . $lid . '.' . $ext;
                    if (move_uploaded_file($file['tmp_name'], $uploadDir . $newName)) {
                        $photoPath = $newName;
                    } else {
                        $error = 'Failed to upload photo.';
                    }
                }
            }

            if (!$error) {
                $db->prepare("UPDATE lawyers SET name=?,mobile=?,about=?,languages=?,state_id=?,city_id=?,residential_address=?,consultation_fee=?,profile_photo=?,updated_at=NOW() WHERE id=?")
                   ->execute([$name,$mobile,$about,$langs,$stateId,$cityId,$address,$fee,$photoPath,$lid]);

                // Update expertise
                $db->prepare("DELETE FROM lawyer_expertise WHERE lawyer_id=?")->execute([$lid]);
                $ins = $db->prepare("INSERT INTO lawyer_expertise (lawyer_id,category_id) VALUES (?,?)");
                foreach ($expertise as $cid) {
                    if ((int)$cid > 0) $ins->execute([$lid,(int)$cid]);
                }

                // Update session name
                $_SESSION['lawyer_name'] = $name;

                $success = 'Profile updated successfully!';
                // Reload
                $ls = $db->prepare("SELECT l.*,s.name AS state_name,c.name AS city_name FROM lawyers l LEFT JOIN states s ON l.state_id=s.id LEFT JOIN cities c ON l.city_id=c.id WHERE l.id=?");
                $ls->execute([$lid]);
                $lawyer = $ls->fetch();

                $expStmt->execute([$lid]);
                $myExpertise = array_column($expStmt->fetchAll(), 'category_id');
            }
        }
    }
}

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

$photoUrl = $lawyer['profile_photo']
    ? '/meevakeel/assets/uploads/lawyers/' . $lawyer['profile_photo']
    : null;

$pageTitle = 'Edit Profile — MeeVakeel';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<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=Playfair+Display:wght@700;800&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<link rel="stylesheet" href="/meevakeel/assets/css/style.css">
<style>
body{background:var(--off-white);font-family:var(--font-body);}
.dash-sidebar{width:240px;min-height:100vh;background:var(--primary-dark);position:fixed;top:0;left:0;z-index:200;overflow-y:auto;}
.dash-main{margin-left:240px;min-height:100vh;}
.dash-topbar{background:white;padding:14px 28px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 2px 8px rgba(0,0,0,.05);}
.dash-content{padding:28px;}
.dash-nav-link{display:flex;align-items:center;gap:12px;padding:11px 20px;color:rgba(255,255,255,.65);font-size:.87rem;font-weight:500;border-radius:8px;margin:2px 10px;text-decoration:none;transition:all .3s;}
.dash-nav-link:hover,.dash-nav-link.active{background:rgba(212,175,55,.15);color:var(--gold);}
.dash-nav-link i{width:18px;text-align:center;}
.nav-section-label{font-size:.68rem;color:rgba(255,255,255,.3);font-weight:700;letter-spacing:.1em;text-transform:uppercase;padding:16px 20px 6px;}
.photo-wrap{width:100px;height:100px;border-radius:50%;border:3px solid var(--gold);overflow:hidden;position:relative;cursor:pointer;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,var(--primary),#1a3a6b);}
.photo-wrap 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:.8rem;flex-direction:column;gap:4px;}
.photo-wrap:hover .photo-overlay{display:flex;}
.section-card{background:white;border-radius:16px;padding:26px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:22px;}
.section-card h6{color:var(--primary);font-size:.9rem;font-weight:800;padding-bottom:12px;border-bottom:2px solid var(--gold);margin-bottom:20px;display:flex;align-items:center;gap:8px;text-transform:uppercase;letter-spacing:.04em;}
.section-card h6 i{color:var(--gold);}
@media(max-width:768px){.dash-sidebar{display:none;}.dash-main{margin-left:0;}}
</style>
</head>
<body>

<!-- Sidebar -->
<div class="dash-sidebar">
  <div style="padding:22px 20px;border-bottom:1px solid rgba(255,255,255,.08);">
    <div style="font-family:var(--font-heading);font-size:1.3rem;font-weight:800;color:white;"><span style="color:var(--gold);">Nyaya</span> Guru</div>
    <div style="font-size:.72rem;color:rgba(255,255,255,.4);margin-top:2px;">Lawyer Portal</div>
  </div>
  <div style="padding:18px 20px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;gap:12px;">
    <div style="width:40px;height:40px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;color:var(--primary);"><?= strtoupper(substr($lawyer['name'],0,1)) ?></div>
    <div>
      <div style="color:white;font-size:.85rem;font-weight:600;"><?= htmlspecialchars(explode(' ',$lawyer['name'])[0]) ?></div>
      <div style="font-size:.7rem;color:rgba(255,193,7,.8);">⏳ <?= ucfirst($lawyer['verification_status']) ?></div>
    </div>
  </div>
  <div class="nav-section-label">Main</div>
  <a href="<?= SITE_URL ?>/lawyer/dashboard.php" class="dash-nav-link">
    <i class="fas fa-tachometer-alt"></i> Dashboard
</a>

<a href="<?= SITE_URL ?>/lawyer/appointments.php" class="dash-nav-link">
    <i class="fas fa-calendar-check"></i> Appointments
</a>

<a href="<?= SITE_URL ?>/lawyer/availability.php" class="dash-nav-link">
    <i class="fas fa-clock"></i> Availability
</a>

<div class="nav-section-label">Account</div>

<a href="<?= SITE_URL ?>/lawyer/profile.php" class="dash-nav-link active">
    <i class="fas fa-user-edit"></i> My Profile
</a>

<a href="<?= SITE_URL ?>/lawyer/logout.php" class="dash-nav-link" style="color:rgba(220,53,69,.8);">
    <i class="fas fa-sign-out-alt"></i> Logout
</a>
</div>

<div class="dash-main">
  <div class="dash-topbar">
    <div>
      <h5 style="margin:0;font-size:1rem;color:var(--primary);">Edit Profile</h5>
      <span style="font-size:.78rem;color:var(--text-light);">Keep your profile accurate and up-to-date</span>
    </div>
    <div style="display:flex;gap:12px;align-items:center;">
      <a href="/lawyer-details.php?id=<?= $lid ?>" target="_blank" style="font-size:.8rem;color:var(--primary);font-weight:600;">
        <i class="fas fa-external-link-alt me-1"></i>View Public Profile
      </a>
      <a href="/lawyer/logout.php" style="color:var(--text-light);font-size:.82rem;">Logout</a>
    </div>
  </div>

  <div class="dash-content">

    <?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; ?>

    <!-- Verification status banner -->
    <?php if ($lawyer['verification_status'] === 'pending'): ?>
    <div style="background:rgba(255,193,7,.08);border:1px solid rgba(255,193,7,.35);border-radius:12px;padding:14px 18px;margin-bottom:22px;">
      <i class="fas fa-hourglass-half me-2" style="color:#b8860b;"></i>
      <strong style="color:#b8860b;font-size:.88rem;">Profile Under Review</strong>
      <span style="color:var(--text-light);font-size:.82rem;"> — Our team is verifying your credentials. This takes 24–48 hours.</span>
    </div>
    <?php elseif ($lawyer['verification_status'] === 'rejected'): ?>
    <div style="background:rgba(220,53,69,.07);border:1px solid rgba(220,53,69,.3);border-radius:12px;padding:14px 18px;margin-bottom:22px;">
      <i class="fas fa-times-circle me-2" style="color:#c0392b;"></i>
      <strong style="color:#c0392b;font-size:.88rem;">Profile Rejected</strong>
      <?php if ($lawyer['rejection_reason']): ?>
      <span style="color:var(--text-light);font-size:.82rem;"> — <?= htmlspecialchars($lawyer['rejection_reason']) ?></span>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="csrf_token" value="<?= generateCSRF() ?>">

      <div class="row g-4">
        <div class="col-lg-8">

          <!-- Personal -->
          <div class="section-card">
            <h6><i class="fas fa-user"></i> Personal Information</h6>
            <div class="row g-3">
              <!-- Profile photo -->
              <div class="col-12">
                <label class="form-label">Profile Photo</label>
                <div style="display:flex;align-items:center;gap:18px;">
                  <div class="photo-wrap" onclick="document.getElementById('photoInput').click()">
                    <?php if ($photoUrl): ?>
                    <img src="<?= $photoUrl ?>?t=<?= time() ?>" alt="Profile" id="photoPreview"
                         onerror="this.style.display='none';">
                    <?php else: ?>
                    <div id="photoInitials" style="font-size:2rem;font-weight:800;color:var(--gold);font-family:var(--font-heading);"><?= strtoupper(substr($lawyer['name'],0,2)) ?></div>
                    <?php endif; ?>
                    <div class="photo-overlay"><i class="fas fa-camera"></i><span>Change</span></div>
                  </div>
                  <div>
                    <div style="font-size:.82rem;color:var(--text-light);line-height:1.7;">
                      Click photo to change.<br>JPG, PNG, GIF — Max 5MB.
                    </div>
                    <input type="file" id="photoInput" name="profile_photo" accept="image/*" style="display:none;"
                           onchange="previewPhoto(this)">
                  </div>
                </div>
              </div>

              <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($lawyer['name']) ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">Email Address</label>
                <input type="email" class="form-control" value="<?= htmlspecialchars($lawyer['email']) ?>" disabled style="background:var(--off-white);">
                <div class="form-text">Email cannot be changed. Contact support.</div>
              </div>
              <div class="col-md-6">
                <label class="form-label">Mobile Number</label>
                <input type="tel" name="mobile" class="form-control" value="<?= htmlspecialchars($lawyer['mobile']) ?>" maxlength="10">
              </div>
              <div class="col-md-6">
                <label class="form-label">Experience</label>
                <input type="text" class="form-control" value="<?= getExperienceLabel($lawyer['experience_years']) ?>" disabled style="background:var(--off-white);">
                <div class="form-text">Contact support to update experience.</div>
              </div>
              <div class="col-md-12">
                <label class="form-label">Languages Known</label>
                <select name="languages[]" class="form-select select2-multi" multiple>
                  <?php
                  $myLangs = array_map('trim', explode(',', $lawyer['languages'] ?? ''));
                  foreach(['English','Hindi','Telugu','Tamil','Kannada','Malayalam','Urdu','Bengali','Marathi','Gujarati','Punjabi','Odia'] as $l):
                    $selected = in_array(strtolower($l), $myLangs) ? 'selected' : '';
                  ?>
                  <option value="<?= strtolower($l) ?>" <?= $selected ?>><?= $l ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-12">
                <label class="form-label">About / Bio</label>
                <textarea name="about" class="form-control" rows="5" placeholder="Describe your experience, specialisations, notable cases, education..."><?= htmlspecialchars($lawyer['about'] ?? '') ?></textarea>
                <div class="form-text">A good bio helps clients trust you. Aim for 100–300 words.</div>
              </div>
            </div>
          </div>

          <!-- Professional -->
          <div class="section-card">
            <h6><i class="fas fa-briefcase"></i> Professional Details</h6>
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">Practice Areas / Expertise</label>
                <select name="expertise[]" class="form-select select2-multi" multiple>
                  <?php foreach ($categories as $c): ?>
                  <option value="<?= $c['id'] ?>" <?= in_array($c['id'], $myExpertise) ? 'selected' : '' ?>><?= $c['name'] ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <?php if ($lawyer['experience_years'] !== '2-4'): ?>
              <div class="col-md-6">
                <label class="form-label">Consultation Fee (₹ per session)</label>
                <div style="position:relative;">
                  <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--text-light);font-weight:700;">₹</span>
                  <input type="number" name="consultation_fee" class="form-control" style="padding-left:28px;"
                         value="<?= (int)$lawyer['consultation_fee'] ?>" min="0" max="50000" step="50">
                </div>
                <div class="form-text">You receive 80% after 20% platform commission.</div>
              </div>
              <?php endif; ?>
              <div class="col-md-6">
                <label class="form-label">Bar Council Number</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($lawyer['bar_council_number'] ?? '') ?>" disabled style="background:var(--off-white);">
                <div class="form-text">Submit a support request to update.</div>
              </div>
            </div>
          </div>

          <!-- Address -->
          <div class="section-card">
            <h6><i class="fas fa-map-marker-alt"></i> Location</h6>
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">Residential Address</label>
                <textarea name="address" class="form-control" rows="2" placeholder="Your address"><?= htmlspecialchars($lawyer['residential_address'] ?? '') ?></textarea>
              </div>
              <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'] ?>" <?= $lawyer['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'] ?>" <?= $lawyer['city_id'] == $c['id'] ? 'selected' : '' ?>><?= $c['name'] ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
          </div>

          <div class="text-end">
            <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 Profile
            </button>
          </div>

        </div>

        <!-- Right sidebar -->
        <div class="col-lg-4">
          <div style="background:white;border-radius:16px;padding:22px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:18px;">
            <h6 style="font-size:.85rem;font-weight:800;color:var(--primary);margin-bottom:16px;text-transform:uppercase;letter-spacing:.05em;">Profile Completeness</h6>
            <?php
            $fields = [
                'Photo'       => !empty($lawyer['profile_photo']),
                'Name'        => !empty($lawyer['name']),
                'About'       => !empty($lawyer['about']),
                'Languages'   => !empty($lawyer['languages']),
                'Expertise'   => !empty($myExpertise),
                'Location'    => !empty($lawyer['city_id']),
            ];
            $done = count(array_filter($fields));
            $pct  = round(($done / count($fields)) * 100);
            ?>
            <div style="background:var(--off-white);border-radius:50px;overflow:hidden;height:8px;margin-bottom:10px;">
              <div style="width:<?= $pct ?>%;height:100%;background:linear-gradient(90deg,var(--primary),var(--gold));border-radius:50px;"></div>
            </div>
            <div style="font-size:.82rem;font-weight:700;color:var(--primary);margin-bottom:14px;"><?= $pct ?>% Complete</div>
            <?php foreach ($fields as $lbl => $done): ?>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-bottom:1px solid var(--border);font-size:.82rem;">
              <span style="color:var(--text);"><?= $lbl ?></span>
              <i class="fas <?= $done ? 'fa-check-circle' : 'fa-circle' ?>" style="color:<?= $done ? 'var(--success)' : 'var(--border)' ?>;font-size:.9rem;"></i>
            </div>
            <?php endforeach; ?>
          </div>

          <div style="background:var(--off-white);border-radius:14px;padding:18px;border:1px solid var(--border);">
            <h6 style="font-size:.82rem;font-weight:700;color:var(--primary);margin-bottom:10px;"><i class="fas fa-shield-alt me-2" style="color:var(--gold);"></i>Account Security</h6>
            <p style="font-size:.78rem;color:var(--text-light);line-height:1.7;margin-bottom:12px;">
              To change your password or update your enrollment card, please contact our support team.
            </p>
            <a href="/pages/contact.php" style="background:var(--primary);color:white;padding:9px 18px;border-radius:8px;font-size:.8rem;font-weight:600;text-decoration:none;display:inline-block;">
              <i class="fas fa-headset me-1"></i>Contact Support
            </a>
          </div>
        </div>
      </div>
    </form>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function(){
  $('.select2-multi').select2({ width:'100%', placeholder:'Select options', allowClear:true });
});

function previewPhoto(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var wrap = input.closest('form').querySelector('.photo-wrap');
      // Remove initials div if present
      var initials = wrap.querySelector('#photoInitials');
      if (initials) initials.style.display = 'none';
      var img = wrap.querySelector('#photoPreview');
      if (!img) {
        img = document.createElement('img');
        img.id = 'photoPreview';
        img.style.cssText = 'width:100%;height:100%;object-fit:cover;';
        wrap.insertBefore(img, wrap.querySelector('.photo-overlay'));
      }
      img.src = e.target.result;
      img.style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  }
}

// State → City
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('/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>
</body>
</html>