<?php
// nyaya-guru/client/dashboard.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
requireUserLogin();

$db   = getDB();
$uid  = $_SESSION['user_id'];
$user = getCurrentUser();

// Stats
$totalAppts = $db->prepare("SELECT COUNT(*) FROM appointments WHERE user_id=?"); $totalAppts->execute([$uid]); $totalAppts=(int)$totalAppts->fetchColumn();
$pending    = $db->prepare("SELECT COUNT(*) FROM appointments WHERE user_id=? AND status='pending'"); $pending->execute([$uid]); $pending=(int)$pending->fetchColumn();
$completed  = $db->prepare("SELECT COUNT(*) FROM appointments WHERE user_id=? AND status='completed'"); $completed->execute([$uid]); $completed=(int)$completed->fetchColumn();

$spent = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM payments WHERE user_id=? AND status='completed'"); $spent->execute([$uid]); $spent=(float)$spent->fetchColumn();

// Recent appointments with lawyer details
$apptStmt = $db->prepare("
    SELECT a.*, l.name AS lawyer_name, l.profile_photo AS lawyer_photo,
           l.experience_years, l.mobile AS lawyer_mobile,
           GROUP_CONCAT(DISTINCT lc.name SEPARATOR ', ') AS practice_areas
    FROM appointments a
    JOIN lawyers l ON a.lawyer_id = l.id
    LEFT JOIN lawyer_expertise le ON l.id = le.lawyer_id
    LEFT JOIN legal_categories lc ON le.category_id = lc.id
    WHERE a.user_id = ?
    GROUP BY a.id
    ORDER BY a.created_at DESC
    LIMIT 10
");
$apptStmt->execute([$uid]);
$appointments = $apptStmt->fetchAll();

// Upcoming (confirmed/pending with future date)
$upcomingStmt = $db->prepare("
    SELECT a.*, l.name AS lawyer_name, l.mobile AS lawyer_mobile
    FROM appointments a
    JOIN lawyers l ON a.lawyer_id = l.id
    WHERE a.user_id = ? AND a.status IN ('pending','confirmed')
    AND (a.appointment_date >= CURDATE() OR a.appointment_date IS NULL)
    ORDER BY a.appointment_date ASC, a.created_at DESC
    LIMIT 3
");
$upcomingStmt->execute([$uid]);
$upcoming = $upcomingStmt->fetchAll();

function apptBadge(string $s): string {
    $m = ['pending'=>['rgba(255,193,7,.15)','#b8860b'],'confirmed'=>['rgba(40,167,69,.12)','#1a7a34'],'completed'=>['rgba(10,35,66,.1)','#0A2342'],'cancelled'=>['rgba(220,53,69,.1)','#c0392b'],'rejected'=>['rgba(220,53,69,.1)','#c0392b'],'ongoing'=>['rgba(23,162,184,.12)','#0c7590']];
    [$bg,$c] = $m[$s] ?? ['rgba(0,0,0,.06)','#555'];
    return "<span style='background:$bg;color:$c;padding:4px 12px;border-radius:50px;font-size:.72rem;font-weight:700;'>".ucfirst($s)."</span>";
}

$pageTitle = 'My Dashboard — Nyaya Guru';
require_once __DIR__ . '/../includes/header.php';
?>

<style>
.client-dash{background:var(--off-white);min-height:80vh;padding:40px 0;}
.stat-card{background:white;border-radius:14px;padding:20px; text-align:center;   justify-content: center;border:1px solid var(--border);box-shadow:var(--shadow);display:flex;align-items:center;gap:30px;height:100%;}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;min-width:48px;}
.stat-num{font-size:1.6rem;font-weight:800;color:var(--primary);font-family:var(--font-heading);}
.stat-lbl{font-size:.76rem;color:var(--text-light);font-weight:500;}
.appt-card{background:white;border-radius:14px;padding:18px 20px;border:1px solid var(--border);margin-bottom:12px;transition:all .25s;}
.appt-card:hover{border-color:var(--gold);box-shadow:var(--shadow);}
</style>

<!-- Header bar -->
<div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);padding:32px 0;">
  <div class="container">
    <div class="row align-items-center">
      <div class="col">
        <div style="font-size:.8rem;color:rgba(255,255,255,.55);margin-bottom:4px;">Welcome back,</div>
        <h2 style="color:white;font-size:1.5rem;margin:0;"><?= htmlspecialchars($user['name']) ?></h2>
        <div style="font-size:.8rem;color:rgba(255,255,255,.55);margin-top:4px;"><?= $user['email'] ?></div>
      </div>
      <div class="col-auto d-flex gap-2">
        <a href="<?= SITE_URL ?>/lawyers.php" class="btn btn-gold" style="font-weight:700;padding:10px 20px;border-radius:10px;font-size:.85rem;">
          <i class="fas fa-search me-2"></i>Find Lawyer
        </a>
        <a href="<?= SITE_URL ?>/client/profile.php" style="background:rgba(255,255,255,.1);color:white;padding:10px 16px;border-radius:10px;font-size:.85rem;font-weight:600;text-decoration:none;border:1px solid rgba(255,255,255,.2);">
          <i class="fas fa-user-edit me-1"></i>Profile
        </a>
        <a href="<?= SITE_URL ?>/logout.php" style="background:rgba(220,53,69,.15);color:#ff8080;padding:10px 16px;border-radius:10px;font-size:.85rem;font-weight:600;text-decoration:none;border:1px solid rgba(220,53,69,.25);">
          <i class="fas fa-sign-out-alt"></i>
        </a>
      </div>
    </div>
  </div>
</div>

<div class="client-dash">
<div class="container">

  <!-- Stat Cards -->
  <div class="row g-3 mb-4">
    <?php
    $stats = [
      ['bg'=>'rgba(10,35,66,.08)', 'color'=>'var(--primary)',  'icon'=>'fas fa-calendar',      'num'=>$totalAppts, 'lbl'=>'Total Consultations'],
      ['bg'=>'rgba(255,193,7,.12)','color'=>'#b8860b',         'icon'=>'fas fa-hourglass-half', 'num'=>$pending,    'lbl'=>'Case Status'],
      ['bg'=>'rgba(40,167,69,.1)', 'color'=>'#1a7a34',         'icon'=>'fas fa-check-circle',   'num'=>$completed,  'lbl'=>'Disposed'],
      ['bg'=>'rgba(212,175,55,.15)','color'=>'var(--gold-dark)','icon'=>'fas fa-rupee-sign',     'num'=>'₹'.number_format($spent,0), 'lbl'=>'Remuneration '],
    ];
    foreach ($stats as $s): ?>
    <div class="col-6 col-md-3">
      <div class="stat-card">
        <div class="stat-icon" style="background:<?= $s['bg'] ?>;color:<?= $s['color'] ?>;"><i class="<?= $s['icon'] ?>"></i></div>
        <div>
          <div class="stat-num"><?= $s['num'] ?></div>
          <div class="stat-lbl"><?= $s['lbl'] ?></div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <div class="row g-4">

    <!-- Left: Appointments list -->
    <div class="col-lg-8">

      <!-- Upcoming -->
      <?php if (!empty($upcoming)): ?>
      <div style="margin-bottom:22px;">
        <h6 style="color:var(--primary);font-size:.88rem;font-weight:800;text-transform:uppercase;letter-spacing:.05em;margin-bottom:14px;">
          <i class="fas fa-clock me-2" style="color:var(--gold);"></i>Upcoming Consultations
        </h6>
        <?php foreach ($upcoming as $u): ?>
        <div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:14px;padding:18px 20px;margin-bottom:10px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
          <div style="width:44px;height:44px;min-width:44px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;color:var(--primary);">
            <?= strtoupper(substr($u['lawyer_name'],0,1)) ?>
          </div>
          <div style="flex:1;">
            <div style="color:white;font-weight:700;font-size:.9rem;">Adv. <?= htmlspecialchars($u['lawyer_name']) ?></div>
            <div style="color:rgba(255,255,255,.6);font-size:.78rem;">
              <?= $u['appointment_date'] ? date('D, d M Y', strtotime($u['appointment_date'])) : 'Date TBD' ?>
              <?= $u['appointment_time'] ? ' · '.date('h:i A', strtotime($u['appointment_time'])) : '' ?>
              · <?= ucfirst(str_replace('_',' ',$u['consultation_type'])) ?>
            </div>
          </div>
          <div>
            <?= apptBadge($u['status']) ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- All appointments -->
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;">
        <h6 style="color:var(--primary);font-size:.88rem;font-weight:800;text-transform:uppercase;letter-spacing:.05em;margin:0;">
          <i class="fas fa-list me-2" style="color:var(--gold);"></i>All Consultations
        </h6>
      </div>

      <?php if (empty($appointments)): ?>
      <div style="background:white;border-radius:16px;padding:60px;text-align:center;border:1px solid var(--border);">
        <i class="fas fa-calendar-plus" style="font-size:3rem;color:var(--border);margin-bottom:16px;display:block;"></i>
        <h5 style="color:var(--primary);">No consultations yet</h5>
        <p style="color:var(--text-light);font-size:.88rem;margin-bottom:20px;">Find a lawyer and book your first consultation.</p>
        <a href="<?= SITE_URL ?>/lawyers.php" class="btn btn-gold" px-4">
          <i class="fas fa-search me-2"></i>Find Lawyers
        </a>
      </div>
      <?php else: ?>
      <?php foreach ($appointments as $a):
        $initials = strtoupper(substr($a['lawyer_name'],0,1));
        $photoUrl = $a['lawyer_photo'] ? '/nyaya-guru/assets/uploads/lawyers/'.$a['lawyer_photo'] : null;
      ?>
      <div class="appt-card">
        <div class="row align-items-center g-2">
          <!-- Lawyer -->
          <div class="col-md-4" style="display:flex;align-items:center;gap:12px;">
            <?php if ($photoUrl): ?>
            <img src="<?= $photoUrl ?>" style="width:42px;height:42px;border-radius:50%;border:2px solid var(--gold);object-fit:cover;" onerror="this.style.display='none';">
            <?php else: ?>
            <div style="width:42px;height:42px;min-width:42px;background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:50%;display:flex;align-items:center;justify-content:center;color:var(--gold);font-weight:800;font-size:.9rem;"><?= $initials ?></div>
            <?php endif; ?>
            <div>
              <div style="font-weight:700;font-size:.88rem;color:var(--primary);">Adv. <?= htmlspecialchars($a['lawyer_name']) ?></div>
              <?php if ($a['practice_areas']): ?>
              <div style="font-size:.72rem;color:var(--text-light);"><?= htmlspecialchars(mb_strimwidth($a['practice_areas'],0,35,'...')) ?></div>
              <?php endif; ?>
            </div>
          </div>
          <!-- Date & type -->
          <div class="col-md-3">
            <div style="font-size:.78rem;color:var(--text-light);font-weight:600;margin-bottom:2px;">
              <?= $a['appointment_date'] ? date('d M Y', strtotime($a['appointment_date'])) : 'Date TBD' ?>
            </div>
            <span style="background:rgba(10,35,66,.07);color:var(--primary);padding:3px 10px;border-radius:50px;font-size:.7rem;font-weight:600;text-transform:capitalize;">
              <?= str_replace('_',' ',$a['consultation_type']) ?>
            </span>
          </div>
          <!-- Booking ID -->
          <div class="col-md-2">
            <div style="font-size:.7rem;color:var(--text-light);font-weight:700;text-transform:uppercase;">Booking ID</div>
            <div style="font-size:.78rem;font-weight:700;color:var(--primary);"><?= $a['booking_id'] ?></div>
          </div>
          <!-- Status & action -->
          <div class="col-md-3" style="text-align:right;">
            <div style="margin-bottom:8px;"><?= apptBadge($a['status']) ?></div>
            <div style="display:flex;gap:6px;justify-content:flex-end;">
              <a href="<?= SITE_URL ?>/lawyer-details.php?id=<?= $a['lawyer_id'] ?>"
                 style="background:var(--off-white);color:var(--primary);padding:5px 12px;border-radius:8px;font-size:.72rem;font-weight:600;text-decoration:none;border:1px solid var(--border);">
                <i class="fas fa-eye me-1"></i>View
              </a>
              <?php if (in_array($a['status'],['pending','confirmed'])): ?>
              <a href="<?= SITE_URL ?>/cancel-appointment.php?id=<?= $a['id'] ?>"
                 style="background:rgba(220,53,69,.07);color:#c0392b;padding:5px 12px;border-radius:8px;font-size:.72rem;font-weight:600;text-decoration:none;border:1px solid rgba(220,53,69,.15);"
                 onclick="return confirm('Cancel this appointment?')">
                Cancel
              </a>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- Right sidebar -->
    <div class="col-lg-4">

      <!-- Quick actions -->
      <div style="background:white;border-radius:16px;padding:22px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:18px;">
        <h6 style="color:var(--primary);font-size:.85rem;font-weight:800;margin-bottom:16px;text-transform:uppercase;letter-spacing:.05em;">Quick Actions</h6>
        <?php
    $actions = [
    [SITE_URL . '/lawyers.php',                    'fas fa-search',           'var(--primary)',   'Find a Lawyer',      'Search verified advocates'],
    [SITE_URL . '/lawyers.php?experience=10+',    'fas fa-user-tie',         'var(--gold-dark)', 'Top Senior Lawyers', '10+ years experience'],
    [SITE_URL . '/client/profile.php',            'fas fa-user-edit',        '#2d6a4f',          'Update Profile',     'Edit your information'],
    [SITE_URL . '/pages/faq.php',                 'fas fa-question-circle',  '#8e44ad',          'Help & FAQ',         'Common questions'],
];
        foreach ($actions as [$url,$icon,$color,$title,$desc]): ?>
        <a href="<?= $url ?>" style="display:flex;align-items:center;gap:12px;padding:12px;border-radius:10px;text-decoration:none;border:1px solid transparent;transition:all .25s;margin-bottom:6px;"
           onmouseover="this.style.background='var(--off-white)';this.style.borderColor='var(--border)'"
           onmouseout="this.style.background='';this.style.borderColor='transparent'">
          <div style="width:38px;height:38px;min-width:38px;background:<?= $color ?>;border-radius:10px;display:flex;align-items:center;justify-content:center;color:white;font-size:.88rem;">
            <i class="<?= $icon ?>"></i>
          </div>
          <div>
            <div style="font-weight:700;font-size:.85rem;color:var(--primary);"><?= $title ?></div>
            <div style="font-size:.75rem;color:var(--text-light);"><?= $desc ?></div>
          </div>
          <i class="fas fa-chevron-right ms-auto" style="color:var(--border);font-size:.7rem;"></i>
        </a>
        <?php endforeach; ?>
      </div>

      <!-- WhatsApp support -->
      <div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:16px;padding:22px;text-align:center;">
        <i class="fab fa-whatsapp" style="font-size:2rem;color:#25D366;margin-bottom:10px;display:block;"></i>
        <h6 style="color:white;margin-bottom:6px;font-size:.9rem;">Need Help?</h6>
        <p style="color:rgba(255,255,255,.6);font-size:.78rem;margin-bottom:14px;">Chat with our support team on WhatsApp</p>
        <a href="https://wa.me/9876543210" target="_blank"
           style="background:#25D366;color:white;padding:10px 20px;border-radius:50px;font-size:.82rem;font-weight:700;text-decoration:none;display:inline-block;">
          <i class="fab fa-whatsapp me-1"></i>Chat Now
        </a>
      </div>
    </div>

  </div>
</div>
</div>

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