<?php
// nyaya-guru/book-consultation.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/auth.php';

if (!isUserLoggedIn()) { 
    redirect(SITE_URL . '/login.php?redirect=' . urlencode($_SERVER['REQUEST_URI']));
}

$db       = getDB();
$lawyerId = (int)($_GET['lawyer_id'] ?? 0);
if (!$lawyerId) { 
    redirect(SITE_URL . '/client/dashboard.php'); 
}

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

$user = getCurrentUser();

if (!$user) {

    session_destroy();

    redirect(SITE_URL . '/login.php');
}
$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRF($_POST['csrf_token'] ?? '')) { $error = 'Invalid request.'; }
    else {
        $type    = sanitize($_POST['consultation_type'] ?? 'chat');
        $date    = sanitize($_POST['appointment_date'] ?? '');
        $time    = sanitize($_POST['appointment_time'] ?? '');
        $desc    = sanitize($_POST['description'] ?? '');

        if (!$date || !$type) { $error = 'Please fill all required fields.'; }
        elseif (strtotime($date) < strtotime('today')) { $error = 'Please select a future date.'; }
        else {
            $bookId = generateBookingID();
            $fee    = $lawyer['experience_years'] === '2-4' ? 0 : $lawyer['consultation_fee'];
            $db->prepare("INSERT INTO appointments (booking_id,user_id,lawyer_id,consultation_type,appointment_date,appointment_time,description,status) VALUES (?,?,?,?,?,?,?,'pending')")
        ->execute([
    $bookId,
    (int)$user['id'],
    $lawyerId,
    $type,
    $date,
    $time,
    $desc
]);
            $apptId = $db->lastInsertId();

            if ($fee > 0) {
                // Create payment record
                $db->prepare("INSERT INTO payments (appointment_id,user_id,lawyer_id,amount,platform_fee,lawyer_payout,status) VALUES (?,?,?,?,?,?,'pending')")
                   ->execute([$apptId,$user['id'],$lawyerId,$fee,round($fee*0.2,2),round($fee*0.8,2)]);
                setFlash('success','Booking confirmed! Please complete payment to finalise. Booking ID: '.$bookId);
            } else {
                setFlash('success','Booking confirmed! Free consultation booked. Booking ID: '.$bookId);
            }
            redirect(SITE_URL . '/client/dashboard.php');
        }
    }
}

$freeConsult = ($lawyer['experience_years'] === '2-4');
$pageTitle   = 'Book Consultation — '.htmlspecialchars($lawyer['name']).' | MeeVakeel';
require_once __DIR__ . '/includes/header.php';
?>

<section class="page-hero">
  <div class="container">
    <nav aria-label="breadcrumb"><ol class="breadcrumb mb-3">
      <li class="breadcrumb-item"><a href="<?= SITE_URL ?>">Home</a></li>
      <li class="breadcrumb-item"><a href="<?= SITE_URL ?>/lawyers.php">Lawyers</a></li>
      <li class="breadcrumb-item"><a href="<?= SITE_URL ?>/lawyer-details.php?id=<?= $lawyerId ?>">Profile</a></li>
      <li class="breadcrumb-item active">Book Consultation</li>
    </ol></nav>
    <h1 class="mb-1">Book <span style="color:var(--gold);">Consultation</span></h1>
  </div>
</section>

<section style="background:var(--off-white);padding:56px 0;">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8">

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

  <!-- Lawyer summary card -->
  <div style="background:white;border-radius:16px;padding:22px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:24px;display:flex;gap:16px;align-items:center;">
    <div style="width:64px;height:64px;min-width:64px;background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:1.4rem;font-weight:800;color:var(--gold);font-family:var(--font-heading);">
      <?= strtoupper(substr($lawyer['name'],0,2)) ?>
    </div>
    <div style="flex:1;">
      <h5 style="margin:0 0 4px;font-size:1rem;">Adv. <?= htmlspecialchars($lawyer['name']) ?></h5>
      <span style="font-size:.8rem;color:var(--text-light);"><?= getExperienceLabel($lawyer['experience_years']) ?> Experience</span>
    </div>
    <div style="text-align:right;">
      <div style="font-size:1.4rem;font-weight:800;color:var(--primary);font-family:var(--font-heading);">
        <?= $freeConsult ? '<span style="color:var(--success);">FREE</span>' : '₹'.number_format($lawyer['consultation_fee'],0) ?>
      </div>
      <div style="font-size:.72rem;color:var(--text-light);">per session</div>
    </div>
  </div>

  <!-- Booking Form -->
  <div style="background:white;border-radius:16px;overflow:hidden;box-shadow:var(--shadow-lg);border:1px solid var(--border);">
    <div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);padding:24px 28px;">
      <h4 style="color:white;margin:0;font-size:1.1rem;">Consultation Details</h4>
    </div>
    <div style="padding:32px;">
      <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= generateCSRF() ?>">

        <div class="row g-4">
          <div class="col-md-6">
            <label class="form-label">Consultation Type <span class="text-danger">*</span></label>
            <select name="consultation_type" class="form-select" required>
              <option value="chat"       <?= ($_POST['consultation_type']??'chat')==='chat'?'selected':'' ?>>💬 Chat</option>
              <option value="audio"      <?= ($_POST['consultation_type']??'')==='audio'?'selected':'' ?>>📞 Audio Call</option>
              <option value="video"      <?= ($_POST['consultation_type']??'')==='video'?'selected':'' ?>>📹 Video Call</option>
              <option value="in_person"  <?= ($_POST['consultation_type']??'')==='in_person'?'selected':'' ?>>🏢 In-Person</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Preferred Date <span class="text-danger">*</span></label>
            <input type="date" name="appointment_date" class="form-control" min="<?= date('Y-m-d') ?>" value="<?= htmlspecialchars($_POST['appointment_date']??'') ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Preferred Time</label>
            <input type="time" name="appointment_time" class="form-control" value="<?= htmlspecialchars($_POST['appointment_time']??'') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Your Name</label>
         <input type="text" 
       name="client_name"
       class="form-control" 
       value="<?= htmlspecialchars($user['name'] ?? '') ?>">
          </div>
          <div class="col-12">
            <label class="form-label">Brief Description of Your Legal Issue <span class="text-danger">*</span></label>
            <textarea name="description" class="form-control" rows="4" placeholder="Briefly describe your legal issue so the lawyer can prepare..." required><?= htmlspecialchars($_POST['description']??'') ?></textarea>
          </div>

          <!-- Fee summary -->
          <div class="col-12">
            <div style="background:var(--off-white);border-radius:12px;padding:18px 20px;border:1px solid var(--border);">
              <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:.88rem;color:var(--text-light);">
                <span>Consultation Fee</span>
                <span style="font-weight:700;color:var(--primary);"><?= $freeConsult ? 'FREE (first 10 min)' : '₹'.number_format($lawyer['consultation_fee'],0) ?></span>
              </div>
              <?php if (!$freeConsult): ?>
              <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:.88rem;color:var(--text-light);">
                <span>Platform Fee (included)</span>
                <span>₹<?= number_format($lawyer['consultation_fee']*0.2,0) ?></span>
              </div>
              <div style="border-top:1px solid var(--border);padding-top:10px;margin-top:10px;display:flex;justify-content:space-between;font-weight:800;color:var(--primary);">
                <span>Total Payable</span>
                <span style="font-size:1.1rem;">₹<?= number_format($lawyer['consultation_fee'],0) ?></span>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="col-12">
            <button type="submit" class="btn btn-gold w-100 py-3" style="font-weight:700;border-radius:12px;font-size:1rem;">
              <i class="fas fa-calendar-check me-2"></i>Confirm Booking
            </button>
            <p style="font-size:.78rem;color:var(--text-light);text-align:center;margin-top:10px;">
              <i class="fas fa-lock me-1" style="color:var(--success);"></i>Secure & Confidential · Payment processed via Razorpay
            </p>
          </div>
        </div>
      </form>
    </div>
  </div>

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