<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name       = sanitize($_POST['name']);
    $email      = sanitizeEmail($_POST['email']);
    $mobile     = sanitize($_POST['mobile']);
    $password   = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $experience = $_POST['experience_years'];
    $fee        = (float)$_POST['consultation_fee'];

    $languages  = sanitize($_POST['languages']);
    $address    = sanitize($_POST['residential_address']);

    $state_id   = (int)$_POST['state_id'];
    $city_id    = (int)$_POST['city_id'];

    $about      = sanitize($_POST['about']);

    $photo = null;

    // Upload Profile Photo
    if (!empty($_FILES['profile_photo']['name'])) {

        $ext = strtolower(pathinfo(
            $_FILES['profile_photo']['name'],
            PATHINFO_EXTENSION
        ));

        $photo = uniqid() . '_' . time() . '.' . $ext;

        $uploadDir = dirname(__DIR__) . '/assets/uploads/profiles/';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        move_uploaded_file(
            $_FILES['profile_photo']['tmp_name'],
            $uploadDir . $photo
        );
    }

    // Insert Lawyer
    $stmt = $db->prepare("
        INSERT INTO lawyers (

            name,
            email,
            mobile,
            password,
            profile_photo,
            experience_years,
            consultation_fee,
            languages,
            residential_address,
            state_id,
            city_id,
            about,
            verification_status,
            status,
            created_at

        ) VALUES (

            ?,?,?,?,?,?,?,?,?,?,?,?,
            'approved',
            1,
            NOW()

        )
    ");

    $stmt->execute([

        $name,
        $email,
        $mobile,
        $password,
        $photo,
        $experience,
        $fee,
        $languages,
        $address,
        $state_id,
        $city_id,
        $about

    ]);

    // Lawyer ID
    $lawyerId = $db->lastInsertId();

    // Save Expertise Categories
    if (!empty($_POST['category_ids'])) {

        $expStmt = $db->prepare("
            INSERT INTO lawyer_expertise (
                lawyer_id,
                category_id
            ) VALUES (?,?)
        ");

        foreach ($_POST['category_ids'] as $cid) {

            $expStmt->execute([
                $lawyerId,
                (int)$cid
            ]);

        }
    }

    setAdminFlash('success', 'Lawyer added successfully.');

    header('Location: ' . SITE_URL . '/admin/lawyers.php');
    exit;
}

adminHead('Add Lawyer');
adminSidebar('lawyers');
?>

<div class="adm-main">

<?php adminTopbar('Add Lawyer'); ?>

<div class="adm-content">

<div class="adm-card" style="max-width:1000px;">

<form method="POST" enctype="multipart/form-data">

<div class="row g-3">

<div class="col-md-6">
<label class="lbl">Full Name</label>
<input type="text" name="name" class="form-ctrl" required>
</div>

<div class="col-md-6">
<label class="lbl">Email</label>
<input type="email" name="email" class="form-ctrl" required>
</div>

<div class="col-md-6">
<label class="lbl">Mobile Number</label>
<input type="text" name="mobile" class="form-ctrl" required>
</div>

<div class="col-md-6">
<label class="lbl">Password</label>
<input type="password" name="password" class="form-ctrl" required>
</div>

<div class="col-md-6">

<label class="lbl">Experience</label>

<select name="experience_years" class="form-ctrl">

<option value="2-4">2-4 Years</option>
<option value="5-10">5-10 Years</option>
<option value="10+">10+ Years</option>

</select>

</div>

<div class="col-md-6">

<label class="lbl">Consultation Fee</label>

<input type="number"
       name="consultation_fee"
       class="form-ctrl">

</div>

<div class="col-md-6">

<label class="lbl">Languages</label>

<input type="text"
       name="languages"
       class="form-ctrl"
       placeholder="English, Hindi, Telugu">

</div>

<div class="col-md-6">

<label class="lbl">Profile Photo</label>

<input type="file"
       name="profile_photo"
       class="form-ctrl">

</div>

<!-- Expertise Categories -->
<div class="col-12">

<label class="lbl">Expertise Categories</label>

<div style="display:grid;
            grid-template-columns:repeat(3,1fr);
            gap:12px;
            margin-top:10px;">

<?php foreach($categories as $cat): ?>

<label style="display:flex;
              align-items:center;
              gap:8px;
              padding:12px;
              border:1px solid var(--border);
              border-radius:10px;
              background:white;
              cursor:pointer;">

    <input type="checkbox"
           name="category_ids[]"
           value="<?= $cat['id'] ?>">

    <span style="font-size:.82rem;font-weight:500;">
        <?= htmlspecialchars($cat['name']) ?>
    </span>

</label>

<?php endforeach; ?>

</div>

</div>

<div class="col-md-6">

<label class="lbl">State</label>

<select name="state_id"
        id="state_id"
        class="form-ctrl">

<option value="">Select State</option>

<?php foreach($states as $s): ?>

<option value="<?= $s['id'] ?>">
    <?= htmlspecialchars($s['name']) ?>
</option>

<?php endforeach; ?>

</select>

</div>

<div class="col-md-6">

<label class="lbl">City</label>

<select name="city_id"
        id="city_id"
        class="form-ctrl">

<option value="">Select City</option>

</select>

</div>

<div class="col-12">

<label class="lbl">Residential Address</label>

<textarea name="residential_address"
          class="form-ctrl"
          rows="3"></textarea>

</div>

<div class="col-12">

<label class="lbl">About Lawyer</label>

<textarea name="about"
          class="form-ctrl"
          rows="5"></textarea>

</div>

</div>

<div style="margin-top:25px;display:flex;gap:10px;">

<button type="submit" class="btn-gold">

    <i class="fas fa-save me-1"></i>
    Add Lawyer

</button>

<a href="<?= SITE_URL ?>/admin/lawyers.php"
   class="btn-sm-edit"
   style="padding:10px 18px;">

   Cancel

</a>

</div>

</form>

</div>

</div>

</div>

<script>

document.getElementById('state_id').addEventListener('change', function() {

    let sid = this.value;

    fetch('<?= SITE_URL ?>/api/get_cities.php?state_id=' + sid)

    .then(r => r.json())

    .then(res => {

        let html = '<option value="">Select City</option>';

        if (res.success) {

            res.data.forEach(c => {

                html += `<option value="${c.id}">${c.name}</option>`;

            });

        }

        document.getElementById('city_id').innerHTML = html;

    });

});

</script>

<?php adminFoot(); ?>