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

$db  = getDB();
$id  = (int)($_GET['id'] ?? 0);
if (!$id) { redirect('/lawyers.php'); }

$stmt = $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=? AND l.status=1
    LIMIT 1");
$stmt->execute([$id]);
$lawyer = $stmt->fetch();
if (!$lawyer) { redirect('/lawyers.php'); }

// Expertise
$exp = $db->prepare("SELECT lc.name, lc.slug FROM lawyer_expertise le JOIN legal_categories lc ON le.category_id=lc.id WHERE le.lawyer_id=?");
$exp->execute([$id]);
$expertise = $exp->fetchAll();

// Reviews
$revStmt = $db->prepare("SELECT r.*, u.name AS client_name FROM reviews r JOIN users u ON r.user_id=u.id WHERE r.lawyer_id=? AND r.is_approved=1 ORDER BY r.created_at DESC LIMIT 10");
$revStmt->execute([$id]);
$reviews = $revStmt->fetchAll();

// Availability
$avStmt = $db->prepare("SELECT * FROM lawyer_availability WHERE lawyer_id=? AND is_available=1 ORDER BY FIELD(day_of_week,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')");
$avStmt->execute([$id]);
$availability = $avStmt->fetchAll();

$freeConsult   = ($lawyer['experience_years'] === '2-4');
$photoUrl      = $lawyer['profile_photo'] ? '/nyaya-guru/assets/uploads/lawyers/'.$lawyer['profile_photo'] : null;
$initials      = strtoupper(substr($lawyer['name'],0,1)).(isset(explode(' ',$lawyer['name'])[1])?strtoupper(substr(explode(' ',$lawyer['name'])[1],0,1)):'');

$pageTitle = 'Adv. '.htmlspecialchars($lawyer['name']).' — MeeVakeel';
require_once __DIR__ . '/includes/header.php';
?>

<!-- Profile Hero -->
<div style="background:linear-gradient(135deg,var(--primary-dark),var(--primary));padding:48px 0 0;">
  <div class="container">
    <nav aria-label="breadcrumb" style="margin-bottom:20px;">
      <ol class="breadcrumb"><li class="breadcrumb-item"><a href="/">Home</a></li><li class="breadcrumb-item"><a href="/lawyers.php">Lawyers</a></li><li class="breadcrumb-item active" style="color:var(--gold);"><?= htmlspecialchars($lawyer['name']) ?></li></ol>
    </nav>
    <div class="row align-items-center g-4 pb-5">
      <div class="col-auto">
        <?php if ($photoUrl): ?>
        <img src="<?= $photoUrl ?>" alt="<?= htmlspecialchars($lawyer['name']) ?>" class="profile-avatar-lg" onerror="this.outerHTML='<div class=\'lawyer-avatar-placeholder\' style=\'width:110px;height:110px;font-size:2rem;\'><?= $initials ?></div>'">
        <?php else: ?>
        <div class="lawyer-avatar-placeholder" style="width:110px;height:110px;font-size:2rem;"><?= $initials ?></div>
        <?php endif; ?>
      </div>
      <div class="col">
        <span class="verified-badge" style="position:static;display:inline-flex;margin-bottom:10px;"><i class="fas fa-check-circle me-1"></i>Verified Lawyer</span>
        <h1 class="profile-name">Adv. <?= htmlspecialchars($lawyer['name']) ?></h1>
        <?php if ($expertise): ?>
        <div class="profile-specialization"><?= implode(' · ', array_column($expertise,'name')) ?></div>
        <?php endif; ?>
        <div class="profile-meta">
          <?php if ($lawyer['city_name']||$lawyer['state_name']): ?>
          <span><i class="fas fa-map-marker-alt"></i><?= htmlspecialchars(trim(($lawyer['city_name']??'').', '.($lawyer['state_name']??''),', ')) ?></span>
          <?php endif; ?>
          <span><i class="fas fa-briefcase"></i><?= getExperienceLabel($lawyer['experience_years']) ?> Experience</span>
          <?php if ($lawyer['languages']): ?>
          <span><i class="fas fa-language"></i><?= htmlspecialchars(str_replace(',', ', ', ucwords($lawyer['languages']))) ?></span>
          <?php endif; ?>
          <span><?= getLawyerRatingStars($lawyer['rating']) ?> <?= number_format($lawyer['rating'],1) ?> (<?= $lawyer['total_reviews'] ?> reviews)</span>
        </div>
      </div>
    </div>
  </div>
  <svg viewBox="0 0 1440 36" xmlns="http://www.w3.org/2000/svg" style="display:block;width:100%;margin-top:-1px;" preserveAspectRatio="none"><path d="M0,18 C480,36 960,0 1440,18 L1440,36 L0,36 Z" fill="#f8f9fc"/></svg>
</div>

<section style="background:var(--off-white);padding:48px 0 72px;">
<div class="container">
<div class="row g-4">

  <!-- Main Content -->
  <div class="col-lg-8">

    <!-- About -->
    <?php if ($lawyer['about']): ?>
    <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:22px;">
      <h5 style="color:var(--primary);margin-bottom:16px;font-size:1rem;"><i class="fas fa-user me-2" style="color:var(--gold);"></i>About</h5>
      <p style="color:var(--text);line-height:1.85;font-size:.9rem;"><?= nl2br(htmlspecialchars($lawyer['about'])) ?></p>
    </div>
    <?php endif; ?>

    <!-- Expertise -->
    <?php if ($expertise): ?>
    <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:22px;">
      <h5 style="color:var(--primary);margin-bottom:16px;font-size:1rem;"><i class="fas fa-gavel me-2" style="color:var(--gold);"></i>Practice Areas</h5>
      <div style="display:flex;flex-wrap:wrap;gap:8px;">
        <?php foreach ($expertise as $e): ?>
        <a href="/lawyers.php?category=<?= $e['slug'] ?>" style="background:rgba(10,35,66,.07);color:var(--primary);padding:7px 16px;border-radius:50px;font-size:.82rem;font-weight:600;text-decoration:none;border:1px solid var(--border);transition:var(--transition);"
           onmouseover="this.style.background='var(--primary)';this.style.color='white'"
           onmouseout="this.style.background='rgba(10,35,66,.07)';this.style.color='var(--primary)'">
           <?= htmlspecialchars($e['name']) ?>
        </a>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Availability -->
    <?php if ($availability): ?>
    <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:22px;">
      <h5 style="color:var(--primary);margin-bottom:16px;font-size:1rem;"><i class="fas fa-calendar-alt me-2" style="color:var(--gold);"></i>Availability</h5>
      <div class="row g-2">
        <?php foreach ($availability as $av): ?>
        <div class="col-sm-4">
          <div style="background:rgba(40,167,69,.07);border:1px solid rgba(40,167,69,.2);border-radius:10px;padding:12px;text-align:center;">
            <div style="font-weight:700;font-size:.88rem;color:var(--primary);"><?= $av['day_of_week'] ?></div>
            <div style="font-size:.78rem;color:var(--text-light);"><?= date('h:i A', strtotime($av['start_time'])) ?> – <?= date('h:i A', strtotime($av['end_time'])) ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Quick info -->
    <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:22px;">
      <h5 style="color:var(--primary);margin-bottom:16px;font-size:1rem;"><i class="fas fa-info-circle me-2" style="color:var(--gold);"></i>Additional Info</h5>
      <div class="row g-3">
        <?php
        $info = [
          ['fas fa-home',        'Home Visit',      $lawyer['home_visit'] ? 'Available' : 'Not Available', $lawyer['home_visit']],
          ['fas fa-hand-holding-heart','Low-Fee Cases', $lawyer['low_fees_case'] ? 'Available' : 'Not Available', $lawyer['low_fees_case']],
          ['fas fa-balance-scale','Pro Bono',       $lawyer['pro_bono'] ? 'Willing' : 'Not Available', $lawyer['pro_bono']],
          ['fas fa-comments',    'Consultations',  $lawyer['total_consultations'].' completed', true],
        ];
        foreach ($info as [$icon,$label,$val,$pos]): ?>
        <div class="col-6 col-md-3">
          <div style="text-align:center;padding:16px;background:var(--off-white);border-radius:12px;">
            <i class="<?= $icon ?>" style="font-size:1.3rem;color:<?= $pos ? 'var(--success)' : 'var(--text-light)' ?>;margin-bottom:8px;display:block;"></i>
            <div style="font-size:.72rem;color:var(--text-light);text-transform:uppercase;font-weight:700;margin-bottom:3px;"><?= $label ?></div>
            <div style="font-size:.82rem;font-weight:600;color:var(--primary);"><?= $val ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Reviews -->
    <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
      <h5 style="color:var(--primary);margin-bottom:20px;font-size:1rem;"><i class="fas fa-star me-2" style="color:var(--gold);"></i>Client Reviews (<?= count($reviews) ?>)</h5>
      <?php if (empty($reviews)): ?>
      <p style="color:var(--text-light);font-size:.88rem;">No reviews yet. Be the first to consult!</p>
      <?php else: ?>
        <?php foreach ($reviews as $r): ?>
        <div style="padding:16px 0;border-bottom:1px solid var(--border);">
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
            <div style="display:flex;align-items:center;gap:10px;">
              <div style="width:36px;height:36px;background:var(--primary);border-radius:50%;display:flex;align-items:center;justify-content:center;color:var(--gold);font-size:.8rem;font-weight:700;"><?= strtoupper(substr($r['client_name'],0,1)) ?></div>
              <div>
                <div style="font-weight:600;font-size:.88rem;color:var(--primary);"><?= htmlspecialchars($r['client_name']) ?></div>
                <div style="font-size:.72rem;color:var(--text-light);"><?= date('d M Y', strtotime($r['created_at'])) ?></div>
              </div>
            </div>
            <div class="stars"><?php for($s=0;$s<5;$s++) echo '<i class="'.($s<$r['rating']?'fas':'far').' fa-star"></i>'; ?></div>
          </div>
          <?php if ($r['review']): ?>
          <p style="font-size:.88rem;color:var(--text-light);margin:0;line-height:1.7;"><?= htmlspecialchars($r['review']) ?></p>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

  </div>

  <!-- Sidebar -->
  <div class="col-lg-4">
    <div class="profile-sidebar-card">
      <div class="consultation-fee-display">
        <div style="font-size:.75rem;text-transform:uppercase;letter-spacing:.07em;opacity:.7;margin-bottom:8px;">Consultation Fee</div>
        <div class="fee-amount">
          <?= $freeConsult ? '<span style="color:var(--gold);">FREE*</span>' : '₹'.number_format($lawyer['consultation_fee'],0) ?>
        </div>
        <div style="font-size:.75rem;opacity:.65;margin-top:4px;">per session (30 min)</div>
        <?php if ($freeConsult): ?>
        <div style="font-size:.72rem;color:var(--gold);margin-top:6px;">*Free 10-min initial consultation</div>
        <?php endif; ?>
      </div>

     <a href="<?= SITE_URL ?>/book-consultation.php?lawyer_id=<?= $lawyer['id'] ?>" 
   class="btn btn-gold w-100 py-3 mb-3"
   style="font-weight:700;border-radius:12px;font-size:.95rem;">

   <i class="fas fa-calendar-check me-2"></i>
   Book Consultation

</a>
      <a href="https://wa.me/<?= preg_replace('/\D/','',$lawyer['mobile']) ?>" target="_blank"
         style="display:block;background:#25D366;color:white;text-align:center;padding:12px;border-radius:12px;font-weight:700;font-size:.88rem;text-decoration:none;margin-bottom:20px;">
        <i class="fab fa-whatsapp me-2"></i>WhatsApp Lawyer
      </a>

      <div style="border-top:1px solid var(--border);padding-top:18px;">
        <?php
        $sideInfo = [
          ['fas fa-briefcase','Experience', getExperienceLabel($lawyer['experience_years'])],
          ['fas fa-map-marker-alt','Location', trim(($lawyer['city_name']??'').($lawyer['state_name']?', '.$lawyer['state_name']:''),', ')],
          ['fas fa-language','Languages', $lawyer['languages'] ? ucwords(str_replace(',',' · ',$lawyer['languages'])) : 'N/A'],
          ['fas fa-star','Rating', number_format($lawyer['rating'],1).' / 5.0'],
          ['fas fa-handshake','Consultations', $lawyer['total_consultations'].' done'],
        ];
        foreach ($sideInfo as [$ic,$lb,$vl]): if (!$vl || $vl === 'N/A, ') continue; ?>
        <div style="display:flex;gap:12px;margin-bottom:14px;align-items:center;">
          <div style="width:34px;height:34px;min-width:34px;background:rgba(10,35,66,.07);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--primary);font-size:.85rem;"><i class="<?= $ic ?>"></i></div>
          <div>
            <div style="font-size:.72rem;font-weight:700;color:var(--text-light);text-transform:uppercase;letter-spacing:.05em;"><?= $lb ?></div>
            <div style="font-size:.88rem;font-weight:600;color:var(--primary);"><?= htmlspecialchars($vl) ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

</div>
</div>
</section>
<?php require_once __DIR__ . '/includes/footer.php'; ?>