<?php
require_once __DIR__.'/includes/functions.php';
$user = require_user();
mj_require_user_feature('appointment_booking', (int)$user['id']);
$pageTitle = 'Appointments';

mj_v288_ensure_schema();
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['create_appointment'])) {
    verify_csrf();
    $companyId = (int)($_POST['company_id'] ?? 0);
    $company = $companyId && table_exists('mj_companies') ? one('SELECT * FROM mj_companies WHERE id=? LIMIT 1',[$companyId]) : null;
    try {
        q('INSERT INTO mj_appointments(user_id,seller_user_id,company_id,listing_id,customer_name,customer_email,customer_phone,appointment_datetime,duration_minutes,status,note,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW())', [
            (int)$user['id'], (int)($company['user_id'] ?? 0), $companyId, (int)($_POST['listing_id'] ?? 0), trim((string)($_POST['customer_name'] ?? $user['name'] ?? '')), trim((string)($_POST['customer_email'] ?? $user['email'] ?? '')), trim((string)($_POST['customer_phone'] ?? $user['phone'] ?? '')), trim((string)($_POST['appointment_datetime'] ?? '')), (int)($_POST['duration_minutes'] ?? 30), 'pending', trim((string)($_POST['note'] ?? ''))
        ]);
        flash('success','Appointment request submitted. Seller/company will confirm soon.');
        redirect('appointments.php');
    } catch(Throwable $e) { flash('error','Unable to submit appointment: '.$e->getMessage()); }
}
$companyId = (int)($_GET['company_id'] ?? 0);
$selectedCompany = $companyId && table_exists('mj_companies') ? one('SELECT * FROM mj_companies WHERE id=? LIMIT 1',[$companyId]) : null;
$myAppointments = table_exists('mj_appointments') ? all_rows('SELECT a.*, co.name company_name FROM mj_appointments a LEFT JOIN mj_companies co ON co.id=a.company_id WHERE a.user_id=? OR a.seller_user_id=? ORDER BY a.id DESC LIMIT 80',[(int)$user['id'],(int)$user['id']]) : [];

include __DIR__.'/includes/header.php';
?>
<section class="mj-section">
  <div class="container">
    <div class="mj-center-shell">
      <?php include __DIR__.'/includes/account-sidebar.php'; ?>
      <div class="mj-center-main">
        <div class="mj-section-title mb-4">
          <div><span class="mj-badge mb-2"><i class="bi bi-calendar-check"></i> Bookings</span><h1 class="h2 fw-bold mb-1">Appointments</h1><p class="text-muted mb-0">Book appointments, track booking requests, confirmations, reschedules and no-shows.</p></div>
        </div>
        
<?php if($selectedCompany): ?>
<div class="mj-center-card mb-4"><div class="card-body"><h5 class="fw-bold">Book appointment with <?=e($selectedCompany['name'] ?? 'Company')?></h5><form method="post" class="row g-3"><?=csrf_input()?><input type="hidden" name="create_appointment" value="1"><input type="hidden" name="company_id" value="<?=e($companyId)?>"><div class="col-md-4"><label class="form-label">Name</label><input class="form-control" name="customer_name" value="<?=e($user['name'] ?? '')?>"></div><div class="col-md-4"><label class="form-label">Email</label><input class="form-control" name="customer_email" value="<?=e($user['email'] ?? '')?>"></div><div class="col-md-4"><label class="form-label">Phone</label><input class="form-control" name="customer_phone" value="<?=e($user['phone'] ?? '')?>"></div><div class="col-md-4"><label class="form-label">Preferred date/time</label><input type="datetime-local" class="form-control" name="appointment_datetime" required></div><div class="col-md-4"><label class="form-label">Duration</label><select class="form-select" name="duration_minutes"><option>30</option><option>45</option><option>60</option></select></div><div class="col-12"><label class="form-label">Message</label><textarea class="form-control" name="note" rows="3" placeholder="Tell the company what you need"></textarea></div><div class="col-12"><button class="btn btn-primary"><i class="bi bi-send me-1"></i>Submit Booking Request</button></div></form></div></div>
<?php endif; ?>
<div class="mj-center-card"><div class="card-body"><h5 class="fw-bold">My Appointments</h5><?php if(!$myAppointments): ?><div class="mj-empty-state p-4 text-center"><i class="bi bi-calendar-x"></i><h5>No appointments yet</h5><p class="text-muted mb-0">When you book or receive an appointment, it will show here.</p></div><?php else: ?><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Date</th><th>Company</th><th>Status</th><th>Note</th></tr></thead><tbody><?php foreach($myAppointments as $a): ?><tr><td><?=e($a['appointment_datetime'] ?? '-')?></td><td><?=e($a['company_name'] ?? '-')?></td><td><?=mj_v288_status_badge($a['status'] ?? '')?></td><td><?=e(mb_strimwidth($a['note'] ?? '',0,80,'...'))?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?></div></div>

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