<?php
// nyaya-guru/register-lawyer.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/auth.php';

if (isLawyerLoggedIn()) { redirect('lawyer/dashboard.php'); }

$db         = getDB();
$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();

$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRF($_POST['csrf_token'] ?? '')) { $error = 'Invalid request.'; }
    else {
        $name       = sanitize($_POST['name'] ?? '');
        $email      = sanitizeEmail($_POST['email'] ?? '');
        $mobile     = sanitize($_POST['mobile'] ?? '');
        $password   = $_POST['password'] ?? '';
        $experience = $_POST['experience'] ?? '';
        $languages  = implode(',', (array)($_POST['languages'] ?? []));
        $expertise  = (array)($_POST['expertise'] ?? []);
        $address    = sanitize($_POST['address'] ?? '');
        $state_id   = (int)($_POST['state_id'] ?? 0);
        $city_id    = (int)($_POST['city_id'] ?? 0);
        $home_visit = isset($_POST['home_visit']) && $_POST['home_visit'] === 'yes' ? 1 : 0;
        $low_fees   = isset($_POST['low_fees']) && $_POST['low_fees'] === 'yes' ? 1 : 0;
        $pro_bono   = isset($_POST['pro_bono']) && $_POST['pro_bono'] === 'yes' ? 1 : 0;
        $fee        = ($experience === '2-4') ? 0 : (float)($_POST['consultation_fee'] ?? 0);
        $category_id = (int)($expertise[0] ?? 0);

        if (!$name || !$email || !$mobile || !$password || !$experience) {
            $error = 'Please fill all required fields.';
        } elseif (!in_array($experience, ['2-4','5-10','10+'])) {
            $error = 'Invalid experience selection.';
        } elseif (!validateEmail($email)) {
            $error = 'Invalid email.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } else {
            $chk = $db->prepare("SELECT id FROM lawyers WHERE email=? OR mobile=?");
            $chk->execute([$email, $mobile]);
            if ($chk->fetch()) {
                $error = 'Email or mobile already registered.';
            } else {
                // Handle file uploads
                $front = $back = null;
                $profilePhoto = null;

if (!empty($_FILES['profile_photo']['name'])) {

    $uploaded = uploadFile(
        $_FILES['profile_photo'],
        'profiles'
    );

    // remove profiles/ from DB value
    $profilePhoto = basename($uploaded);
}
                foreach (['enrollment_front' => 'lawyers', 'enrollment_back' => 'lawyers'] as $field => $dir) {
                    if (!empty($_FILES[$field]['name'])) {
                        $path = uploadFile($_FILES[$field], $dir);
                        if ($field === 'enrollment_front') $front = $path;
                        else $back = $path;
                    }
                }
                $hashed = hashPassword($password);
               $sql = "INSERT INTO lawyers (

    name,
    email,
    mobile,
    password,
    profile_photo,
    experience_years,
    consultation_fee,
    languages,
    residential_address,
    state_id,
    city_id,
    home_visit,
    low_fees_case,
    pro_bono,
    enrollment_card_front,
    enrollment_card_back,
    verification_status,
    status,
    category_id

) VALUES (

    ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
    'pending',
    1,
    ?

)";
               $db->prepare($sql)->execute([

    $name,
    $email,
    $mobile,
    $hashed,
    $profilePhoto,
    $experience,
    $fee,
    $languages,
    $address,
    $state_id,
    $city_id,
    $home_visit,
    $low_fees,
    $pro_bono,
    $front,
    $back,
    $category_id

]);
                $lid = $db->lastInsertId();

                // Save expertise
                $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]);
                }

                setFlash('success', 'Registration submitted! Our team will verify and approve your profile within 48 hours.');
              redirect('/nyaya-guru/lawyer/login.php');
            }
        }
    }
}

$pageTitle = 'Lawyer Registration — MeeVakeel';
require_once __DIR__ . '/includes/header.php';
?>

<!-- Page Hero -->
<section class="page-hero">
  <div class="container">
    <nav aria-label="breadcrumb"><ol class="breadcrumb mb-3">
      <li class="breadcrumb-item"><a href="/">Home</a></li>
      <li class="breadcrumb-item active">Lawyer Registration</li>
    </ol></nav>
    <h1 class="mb-1">Lawyer Registration — <span style="color:var(--gold);">Freelance Opportunity</span></h1>
    <p style="color:rgba(255,255,255,.72);max-width:560px;">Register free, connect with verified clients, and grow your legal practice online.</p>
  </div>
</section>

<!-- Benefits bar -->
<div style="background:var(--gold);padding:14px 0;">
  <div class="container">
    <div class="row g-3 text-center">
      <?php foreach(['✅ 100% Free Registration','📞 Direct Client Calls','💰 Stage-wise Billing','🏠 Work from Anywhere'] as $b): ?>
      <div class="col-6 col-md-3" style="font-size:.85rem;font-weight:700;color:var(--primary);"><?= $b ?></div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<section style="background:var(--off-white);padding:56px 0;">
<div class="container">

  <?php if ($error): ?>
  <div class="alert alert-danger rounded-3 border-0 mb-4"><i class="fas fa-exclamation-circle me-2"></i><?= $error ?></div>
  <?php endif; ?>

  <!-- Eligibility note -->
  <div style="background:rgba(10,35,66,.06);border-left:4px solid var(--gold);border-radius:0 10px 10px 0;padding:14px 18px;margin-bottom:30px;font-size:.88rem;color:var(--primary);">
    <strong><i class="fas fa-info-circle me-2" style="color:var(--gold);"></i>Eligibility:</strong>
    Lawyers with <strong>2+ years</strong> of practice are eligible. Lawyers with 2–4 yrs must offer a free 10-min initial consultation. Lawyers with 5+ yrs can set their own fees.
  </div>

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

      <!-- ── SECTION 1: Personal ── -->
      <div class="col-12">
        <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
          <h5 class="form-section-title"><i class="fas fa-user"></i> Section 1 — Personal Information</h5>
          <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" placeholder="Enter your full name" value="<?= htmlspecialchars($_POST['name']??'') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Email Address <span class="text-danger">*</span></label>
              <input type="email" name="email" class="form-control" placeholder="your@email.com" value="<?= htmlspecialchars($_POST['email']??'') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Mobile Number <span class="text-danger">*</span></label>
              <input type="tel" name="mobile" class="form-control" placeholder="10-digit mobile" maxlength="10" value="<?= htmlspecialchars($_POST['mobile']??'') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Password <span class="text-danger">*</span></label>
              <input type="password" name="password" class="form-control" placeholder="Min 6 characters" required>
            </div>
            <div class="col-md-6">

    <label class="form-label">
        Profile Photo
    </label>

    <input type="file"
           name="profile_photo"
           class="form-control"
           accept=".jpg,.jpeg,.png">

</div>
            <div class="col-md-6">
              <label class="form-label">Languages Known <span class="text-danger">*</span></label>
              <select name="languages[]" class="form-select select2-multi" multiple required>
                <?php foreach(['English','Hindi','Telugu','Tamil','Kannada','Malayalam','Urdu','Bengali','Marathi','Gujarati','Punjabi','Odia'] as $l): ?>
                <option value="<?= strtolower($l) ?>" <?= in_array(strtolower($l),(array)($_POST['languages']??[])) ? 'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- ── SECTION 2: Professional ── -->
      <div class="col-12">
        <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
          <h5 class="form-section-title"><i class="fas fa-briefcase"></i> Section 2 — Professional Information</h5>
          <div class="row g-3">
            <div class="col-md-12">
              <label class="form-label">Area of Law Expertise <span class="text-danger">*</span></label>
              <select name="expertise[]" class="form-select select2-multi" multiple required>
                <?php foreach ($categories as $c): ?>
                <option value="<?= $c['id'] ?>" <?= in_array($c['id'],(array)($_POST['expertise']??[])) ? 'selected':'' ?>><?= $c['name'] ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Years of Experience <span class="text-danger">*</span></label>
              <select name="experience" class="form-select" required onchange="toggleFeeField(this.value)">
                <option value="">Select Experience</option>
                <option value="2-4"  <?= ($_POST['experience']??'')==='2-4'?'selected':'' ?>>2–4 Years (Free Initial Consultation)</option>
                <option value="5-10" <?= ($_POST['experience']??'')==='5-10'?'selected':'' ?>>5–10 Years</option>
                <option value="10+"  <?= ($_POST['experience']??'')==='10+'?'selected':'' ?>>10+ Years</option>
              </select>
              <div class="form-text text-danger fw-semibold">Lawyers with less than 2 years are not eligible.</div>
            </div>
            <div class="col-md-6" id="feeField" style="<?= ($_POST['experience']??'')==='2-4'?'display:none':'' ?>">
              <label class="form-label">Consultation Fee (₹ per session)</label>
              <input type="number" name="consultation_fee" class="form-control" placeholder="e.g. 500" min="0" value="<?= htmlspecialchars($_POST['consultation_fee']??'') ?>">
              <div class="form-text">Leave 0 if offering free initial session</div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Enrollment Card — Front <span class="text-danger">*</span></label>
              <div class="upload-area" onclick="document.getElementById('ef').click()">
                <i class="fas fa-upload"></i>
                <p>Click to upload (PDF, JPG, PNG)</p>
                <span id="ef_name" style="font-size:.78rem;color:var(--primary);font-weight:600;"></span>
              </div>
              <input type="file" id="ef" name="enrollment_front" accept=".pdf,.jpg,.jpeg,.png" style="display:none" onchange="document.getElementById('ef_name').textContent=this.files[0]?.name||''">
            </div>
            <div class="col-md-6">
              <label class="form-label">Enrollment Card — Back <span class="text-danger">*</span></label>
              <div class="upload-area" onclick="document.getElementById('eb').click()">
                <i class="fas fa-upload"></i>
                <p>Click to upload (PDF, JPG, PNG)</p>
                <span id="eb_name" style="font-size:.78rem;color:var(--primary);font-weight:600;"></span>
              </div>
              <input type="file" id="eb" name="enrollment_back" accept=".pdf,.jpg,.jpeg,.png" style="display:none" onchange="document.getElementById('eb_name').textContent=this.files[0]?.name||''">
            </div>
          </div>
        </div>
      </div>

      <!-- ── SECTION 3: Address ── -->
      <div class="col-12">
        <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
          <h5 class="form-section-title"><i class="fas fa-map-marker-alt"></i> Section 3 — Address Information</h5>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Residential Address <span class="text-danger">*</span></label>
              <textarea name="address" class="form-control" rows="2" placeholder="Your residential address" required><?= htmlspecialchars($_POST['address']??'') ?></textarea>
            </div>
            <div class="col-md-6">
              <label class="form-label">Select State <span class="text-danger">*</span></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'] ?>" <?= ($_POST['state_id']??'')==$s['id']?'selected':'' ?>><?= $s['name'] ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Select City <span class="text-danger">*</span></label>
              <select name="city_id" id="city_id" class="form-select">
                <option value="">-- Select State First --</option>
                <?php
                if (!empty($_POST['state_id'])) {
                    $cities = $db->prepare("SELECT * FROM cities WHERE state_id=? AND status=1 ORDER BY name");
                    $cities->execute([$_POST['state_id']]);
                    foreach ($cities->fetchAll() as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= ($_POST['city_id']??'')==$c['id']?'selected':'' ?>><?= $c['name'] ?></option>
                    <?php endforeach;
                }
                ?>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- ── SECTION 4: Availability ── -->
      <div class="col-12">
        <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
          <h5 class="form-section-title"><i class="fas fa-calendar-check"></i> Section 4 — Availability</h5>
          <div class="row g-3">
            <?php
            $avFields = [
              ['home_visit','Available for Home Visit?'],
              ['low_fees','Available for Low Fees Cases?'],
              ['pro_bono','Willing to Take Pro Bono Matters?'],
            ];
            foreach ($avFields as [$fld, $lbl]): ?>
            <div class="col-md-4">
              <label class="form-label"><?= $lbl ?> <span class="text-danger">*</span></label>
              <select name="<?= $fld ?>" class="form-select" required>
                <option value="">Select</option>
                <option value="yes" <?= ($_POST[$fld]??'')==='yes'?'selected':'' ?>>Yes</option>
                <option value="no"  <?= ($_POST[$fld]??'')==='no'?'selected':'' ?>>No</option>
              </select>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

      <div class="col-12 text-center">
        <button type="submit" class="btn btn-gold btn-lg px-5 py-3" style="font-weight:700;border-radius:12px;font-size:1rem;">
          <i class="fas fa-paper-plane me-2"></i>Submit Registration
        </button>
        <p style="font-size:.8rem;color:var(--text-light);margin-top:12px;">By registering you agree to our <a href="/pages/terms.php">Terms & Conditions</a></p>
      </div>

    </div><!-- /row -->
  </form>
</div>
</section>

<script>
function toggleFeeField(val) {
  document.getElementById('feeField').style.display = val === '2-4' ? 'none' : '';
}
// 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 State First --</option>'; return; }
 fetch('/nyaya-guru/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'; ?>