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

$db = getDB();

$id = (int)($_GET['id'] ?? 0);

$stmt = $db->prepare("
    SELECT *
    FROM lawyers
    WHERE id=?
");

$stmt->execute([$id]);

$lawyer = $stmt->fetch();

if (!$lawyer) {
    die('Lawyer not found');
}

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

/* CITIES */
$cities = [];

if ($lawyer['state_id']) {

    $c = $db->prepare("
        SELECT *
        FROM cities
        WHERE state_id=?
        ORDER BY name
    ");

    $c->execute([$lawyer['state_id']]);

    $cities = $c->fetchAll();
}

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

/* SELECTED EXPERTISE */
$selectedCategories = $db->prepare("
    SELECT category_id
    FROM lawyer_expertise
    WHERE lawyer_id=?
");

$selectedCategories->execute([$id]);

$selectedCategoryIds = array_column(
    $selectedCategories->fetchAll(),
    'category_id'
);

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

    $name       = sanitize($_POST['name'] ?? '');
    $email      = sanitizeEmail($_POST['email'] ?? '');
    $mobile     = sanitize($_POST['mobile'] ?? '');

    $experience = $_POST['experience_years'] ?? '';

    $fee        = (float)($_POST['consultation_fee'] ?? 0);

    $languages  = sanitize($_POST['languages'] ?? '');

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

    $state_id   = (int)($_POST['state_id'] ?? 0);

    $city_id    = (int)($_POST['city_id'] ?? 0);

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

    $photo = $lawyer['profile_photo'];

    /* UPLOAD NEW PHOTO */
    if (!empty($_FILES['profile_photo']['name'])) {

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

        $fileName = 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 . $fileName
        );

        $photo = $fileName;
    }

    /* UPDATE LAWYER */
    $update = $db->prepare("
        UPDATE lawyers SET

            name=?,
            email=?,
            mobile=?,
            profile_photo=?,
            experience_years=?,
            consultation_fee=?,
            languages=?,
            residential_address=?,
            state_id=?,
            city_id=?,
            about=?,
            updated_at=NOW()

        WHERE id=?
    ");

    $update->execute([

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

    ]);

    /* REMOVE OLD EXPERTISE */
    $db->prepare("
        DELETE FROM lawyer_expertise
        WHERE lawyer_id=?
    ")->execute([$id]);

    /* INSERT NEW EXPERTISE */
    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([
                $id,
                (int)$cid
            ]);

        }
    }

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

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

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

<div class="adm-main">

<?php adminTopbar('Edit 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">

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

<label class="lbl">Full Name</label>

<input type="text"
       name="name"
       class="form-ctrl"
       value="<?= htmlspecialchars($lawyer['name']) ?>">

</div>

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

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

<input type="email"
       name="email"
       class="form-ctrl"
       value="<?= htmlspecialchars($lawyer['email']) ?>">

</div>

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

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

<input type="text"
       name="mobile"
       class="form-ctrl"
       value="<?= htmlspecialchars($lawyer['mobile']) ?>">

</div>

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

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

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

<option value="2-4"
<?= $lawyer['experience_years']=='2-4'?'selected':'' ?>>
2-4 Years
</option>

<option value="5-10"
<?= $lawyer['experience_years']=='5-10'?'selected':'' ?>>
5-10 Years
</option>

<option value="10+"
<?= $lawyer['experience_years']=='10+'?'selected':'' ?>>
10+ Years
</option>

</select>

</div>

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

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

<input type="number"
       name="consultation_fee"
       class="form-ctrl"
       value="<?= $lawyer['consultation_fee'] ?>">

</div>

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

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

<input type="text"
       name="languages"
       class="form-ctrl"
       value="<?= htmlspecialchars($lawyer['languages']) ?>">

</div>

<!-- EXPERTISE -->
<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'] ?>"

<?= in_array($cat['id'], $selectedCategoryIds)
? 'checked'
: '' ?>>

<span style="font-size:.82rem;font-weight:500;">

<?= htmlspecialchars($cat['name']) ?>

</span>

</label>

<?php endforeach; ?>

</div>

</div>

<!-- STATE -->
<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'] ?>"
<?= $lawyer['state_id']==$s['id']?'selected':'' ?>>

<?= $s['name'] ?>

</option>

<?php endforeach; ?>

</select>

</div>

<!-- CITY -->
<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>

<?php foreach ($cities as $c): ?>

<option value="<?= $c['id'] ?>"
<?= $lawyer['city_id']==$c['id']?'selected':'' ?>>

<?= $c['name'] ?>

</option>

<?php endforeach; ?>

</select>

</div>

<!-- ADDRESS -->
<div class="col-12">

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

<textarea name="residential_address"
          class="form-ctrl"
          rows="3"><?= htmlspecialchars($lawyer['residential_address']) ?></textarea>

</div>

<!-- ABOUT -->
<div class="col-12">

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

<textarea name="about"
          class="form-ctrl"
          rows="5"><?= htmlspecialchars($lawyer['about']) ?></textarea>

</div>

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

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

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

</div>

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

<?php if ($lawyer['profile_photo']): ?>

<img src="<?= SITE_URL ?>/assets/uploads/profiles/<?= $lawyer['profile_photo'] ?>"
     style="width:90px;
            height:90px;
            object-fit:cover;
            border-radius:10px;
            border:2px solid var(--gold);">

<?php endif; ?>

</div>

</div>

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

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

Update 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() {

    var 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(); ?>