<?php
session_start();
$page_title = 'Shifts';
$active_nav = 'shifts';
include("includes/header.php");
if (!$is_admin) { header("Location: dashboard.php"); exit; }

$success = $error = "";
$action  = $_GET['action'] ?? $_POST['action'] ?? '';
$today   = date('Y-m-d');
$view_date = $_GET['date'] ?? $today;

// Clock In / Out
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'clock') {
    $staff_id  = (int)($_POST['staff_id']  ?? 0);
    $clock_act = $_POST['clock_act'] ?? '';

    // Verify staff belongs to this restaurant
    $chk = $conn->prepare("SELECT id FROM users WHERE id=? AND restaurant_id=? AND role IN('staff','waiter')");
    $chk->bind_param("ii", $staff_id, $__rid); $chk->execute();
    if (!$chk->get_result()->fetch_assoc()) { $error = "Staff not found."; }
    else {
        if ($clock_act === 'in') {
            // Check not already clocked in today
            $ex = $conn->prepare("SELECT id FROM staff_shifts WHERE user_id=? AND shift_date=? AND clock_in IS NOT NULL AND clock_out IS NULL");
            $ex->bind_param("is", $staff_id, $view_date); $ex->execute();
            if ($ex->get_result()->num_rows > 0) { $error = "Already clocked in today."; }
            else {
                $ins = $conn->prepare("INSERT INTO staff_shifts(restaurant_id,user_id,shift_date,clock_in) VALUES(?,?,?,NOW())");
                $ins->bind_param("iis", $__rid, $staff_id, $view_date); $ins->execute();
                $success = "Clocked in successfully.";
            }
        } elseif ($clock_act === 'out') {
            $upd = $conn->prepare("UPDATE staff_shifts SET clock_out=NOW() WHERE user_id=? AND shift_date=? AND clock_out IS NULL");
            $upd->bind_param("is", $staff_id, $view_date); $upd->execute();
            $success = "Clocked out successfully.";
        }
    }
}

// Create scheduled shift
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'schedule') {
    $staff_id   = (int)($_POST['staff_id']   ?? 0);
    $shift_date = $_POST['shift_date']   ?? $today;
    $note       = trim($_POST['note']    ?? '');
    $ins = $conn->prepare("INSERT INTO staff_shifts(restaurant_id,user_id,shift_date,note) VALUES(?,?,?,?)");
    $ins->bind_param("iiss", $__rid, $staff_id, $shift_date, $note); $ins->execute();
    $success = "Shift scheduled.";
}

// Delete shift
if ($action === 'delete' && isset($_POST['id'])) {
    $sid = (int)$_POST['id'];
    $del = $conn->prepare("DELETE FROM staff_shifts WHERE id=? AND restaurant_id=?");
    $del->bind_param("ii", $sid, $__rid); $del->execute();
    header("Location: shifts.php?date=$view_date&msg=deleted"); exit;
}

$msg = $_GET['msg'] ?? '';
if ($msg === 'deleted') $success = "Shift removed.";

// Fetch all active staff
$staff_list = $conn->prepare("SELECT id,name,role FROM users WHERE restaurant_id=? AND role IN('staff','waiter') AND status=1 ORDER BY name");
$staff_list->bind_param("i", $__rid); $staff_list->execute();
$staff_list = $staff_list->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch shifts for selected date
$shifts = $conn->prepare("SELECT ss.*,u.name as staff_name,u.role as staff_role
    FROM staff_shifts ss
    LEFT JOIN users u ON ss.user_id=u.id
    WHERE ss.restaurant_id=? AND ss.shift_date=?
    ORDER BY ss.clock_in ASC, u.name ASC");
$shifts->bind_param("is", $__rid, $view_date); $shifts->execute();
$shifts = $shifts->get_result();

// Weekly summary (Mon-Sun of current week)
$week_start = date('Y-m-d', strtotime('monday this week', strtotime($view_date)));
$week_end   = date('Y-m-d', strtotime('sunday this week', strtotime($view_date)));
$weekly_shifts = $conn->prepare("SELECT u.name,ss.shift_date,ss.clock_in,ss.clock_out
    FROM staff_shifts ss LEFT JOIN users u ON ss.user_id=u.id
    WHERE ss.restaurant_id=? AND ss.shift_date BETWEEN ? AND ?
    ORDER BY ss.shift_date,u.name");
$weekly_shifts->bind_param("iss", $__rid, $week_start, $week_end);
$weekly_shifts->execute();
$weekly_shifts = $weekly_shifts->get_result();

$staff_on_today = $conn->prepare("SELECT COUNT(DISTINCT user_id) FROM staff_shifts WHERE restaurant_id=? AND shift_date=? AND clock_in IS NOT NULL");
$staff_on_today->bind_param("is", $__rid, $today); $staff_on_today->execute();
$staff_on_today = $staff_on_today->get_result()->fetch_row()[0];

$clocked_in = $conn->prepare("SELECT COUNT(*) FROM staff_shifts WHERE restaurant_id=? AND shift_date=? AND clock_in IS NOT NULL AND clock_out IS NULL");
$clocked_in->bind_param("is", $__rid, $today); $clocked_in->execute();
$clocked_in = $clocked_in->get_result()->fetch_row()[0];
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Shifts</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Schedule staff and track clock-in / clock-out</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <button class="btn btn-secondary btn-md" onclick="openModal('scheduleModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
      Schedule Shift
    </button>
    <button class="btn btn-primary btn-md" onclick="openModal('clockModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
      Clock In / Out
    </button>
  </div>
</div>

<!-- Today Summary -->
<div class="grid-3" style="margin-bottom:24px">
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--primary);display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--primary-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Total Staff</div><div style="font-size:1.3rem;font-weight:800;color:var(--primary)"><?php echo count($staff_list); ?></div></div>
  </div>
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--success);display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--success-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Clocked In Now</div><div style="font-size:1.3rem;font-weight:800;color:var(--success)"><?php echo $clocked_in; ?></div></div>
  </div>
  <div class="card" style="padding:18px 20px;border-top:3px solid var(--warning);display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--warning-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--warning)" stroke-width="2" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Worked Today</div><div style="font-size:1.3rem;font-weight:800;color:var(--warning)"><?php echo $staff_on_today; ?></div></div>
  </div>
</div>

<?php if ($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<!-- Date navigation -->
<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap">
  <a href="?date=<?php echo date('Y-m-d', strtotime('-1 day', strtotime($view_date))); ?>"
     class="btn btn-secondary btn-sm">← Prev</a>
  <form method="GET" style="display:flex;align-items:center;gap:8px">
    <input type="date" name="date" value="<?php echo $view_date; ?>"
           style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px;font-size:.83rem;font-family:var(--font);outline:none"
           onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'" onchange="this.form.submit()">
    <button type="submit" class="btn btn-secondary btn-sm">Go</button>
  </form>
  <a href="?date=<?php echo date('Y-m-d', strtotime('+1 day', strtotime($view_date))); ?>"
     class="btn btn-secondary btn-sm">Next →</a>
  <span style="font-size:.95rem;font-weight:700;color:var(--text)">
    <?php echo date('l, F j, Y', strtotime($view_date)); ?>
    <?php if ($view_date === $today): ?><span style="font-size:.72rem;color:var(--primary);background:var(--primary-bg);padding:2px 8px;border-radius:20px;font-weight:700;margin-left:6px">Today</span><?php endif; ?>
  </span>
</div>

<div class="grid-2" style="align-items:start">

  <!-- Shift log for selected date -->
  <div class="card">
    <div class="card-header">
      <h3>Shifts — <?php echo date('M j, Y', strtotime($view_date)); ?></h3>
    </div>
    <?php if ($shifts->num_rows === 0): ?>
      <div style="padding:48px;text-align:center;color:var(--text-muted)">
        <p style="font-weight:700;margin-bottom:4px">No shifts this day</p>
        <p style="font-size:.82rem">Schedule a shift or use Clock In</p>
      </div>
    <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
      <thead><tr><th>Staff</th><th>Clock In</th><th>Clock Out</th><th>Hours</th><th></th></tr></thead>
      <tbody>
      <?php while ($sh = $shifts->fetch_assoc()):
        $clocked_in_val  = $sh['clock_in']  ? date('g:i A', strtotime($sh['clock_in']))  : '—';
        $clocked_out_val = $sh['clock_out'] ? date('g:i A', strtotime($sh['clock_out'])) : '—';
        $hours = '';
        if ($sh['clock_in'] && $sh['clock_out']) {
          $diff = strtotime($sh['clock_out']) - strtotime($sh['clock_in']);
          $hours = round($diff / 3600, 1) . 'h';
        } elseif ($sh['clock_in']) {
          $hours = '⏳ Active';
        }
        $role_label = $sh['staff_role'] === 'waiter' ? 'Waiter' : 'Staff';
      ?>
        <tr>
          <td>
            <div style="font-weight:700;font-size:.84rem"><?php echo htmlspecialchars($sh['staff_name']); ?></div>
            <span class="badge <?php echo $sh['staff_role']==='waiter'?'badge-success':'badge-primary'; ?>" style="margin-top:3px"><?php echo $role_label; ?></span>
          </td>
          <td style="font-size:.82rem;color:<?php echo $sh['clock_in']?'var(--success)':'var(--text-muted)'; ?>;font-weight:600"><?php echo $clocked_in_val; ?></td>
          <td style="font-size:.82rem;color:<?php echo $sh['clock_out']?'var(--error)':'var(--text-muted)'; ?>;font-weight:600"><?php echo $clocked_out_val; ?></td>
          <td style="font-weight:700;color:var(--primary)"><?php echo $hours ?: '—'; ?></td>
          <td>
            <form method="POST" style="display:inline" onsubmit="return confirm('Remove this shift?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?php echo $sh['id']; ?>">
              <button class="btn btn-danger btn-sm" style="padding:5px 8px">✕</button>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
</div>
    <?php endif; ?>
  </div>

  <!-- Weekly Overview -->
  <div class="card">
    <div class="card-header"><h3>This Week</h3><span style="font-size:.75rem;color:var(--text-muted)"><?php echo date('M j',strtotime($week_start)).' – '.date('M j',strtotime($week_end)); ?></span></div>
    <div class="card-body" style="padding:16px 20px">
      <?php
      $week_by_staff = [];
      while ($ws = $weekly_shifts->fetch_assoc()) {
        $n = $ws['name'];
        if (!isset($week_by_staff[$n])) $week_by_staff[$n] = ['days'=>0,'hours'=>0];
        $week_by_staff[$n]['days']++;
        if ($ws['clock_in'] && $ws['clock_out']) {
          $week_by_staff[$n]['hours'] += round((strtotime($ws['clock_out']) - strtotime($ws['clock_in']))/3600,1);
        }
      }
      if (empty($week_by_staff)):
      ?>
        <p style="text-align:center;color:var(--text-muted);padding:24px 0;font-size:.84rem">No shifts this week yet.</p>
      <?php else: foreach ($week_by_staff as $sname => $sdata): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-bottom:1px solid var(--border)">
          <div>
            <div style="font-size:.84rem;font-weight:700"><?php echo htmlspecialchars($sname); ?></div>
            <div style="font-size:.72rem;color:var(--text-muted)"><?php echo $sdata['days']; ?> day<?php echo $sdata['days']!==1?'s':''; ?> scheduled</div>
          </div>
          <?php if ($sdata['hours'] > 0): ?>
          <div style="font-weight:800;color:var(--primary);font-size:.9rem"><?php echo $sdata['hours']; ?>h</div>
          <?php endif; ?>
        </div>
      <?php endforeach; endif; ?>
    </div>
  </div>

</div>

<!-- Clock In/Out Modal -->
<div class="modal-backdrop" id="clockModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Clock In / Out</h3>
      <button class="modal-close" onclick="closeModal('clockModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="clock">
      <div class="modal-body">
        <div class="form-group">
          <label>Select Staff Member</label>
          <select name="staff_id" class="form-control" required>
            <option value="">— Choose staff —</option>
            <?php foreach ($staff_list as $s): ?>
            <option value="<?php echo $s['id']; ?>"><?php echo htmlspecialchars($s['name']); ?> (<?php echo ucfirst($s['role']); ?>)</option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label>Action</label>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
            <label style="cursor:pointer;display:flex;align-items:center;gap:10px;padding:14px 16px;border:2px solid var(--border);border-radius:10px;transition:all .2s" id="lbl-in">
              <input type="radio" name="clock_act" value="in" style="accent-color:var(--success)" onchange="document.getElementById('lbl-in').style.borderColor='var(--success)';document.getElementById('lbl-out').style.borderColor='var(--border)'">
              <span>
                <div style="font-weight:700;color:var(--success)">Clock In</div>
                <div style="font-size:.72rem;color:var(--text-muted)">Start shift</div>
              </span>
            </label>
            <label style="cursor:pointer;display:flex;align-items:center;gap:10px;padding:14px 16px;border:2px solid var(--border);border-radius:10px;transition:all .2s" id="lbl-out">
              <input type="radio" name="clock_act" value="out" style="accent-color:var(--error)" onchange="document.getElementById('lbl-out').style.borderColor='var(--error)';document.getElementById('lbl-in').style.borderColor='var(--border)'">
              <span>
                <div style="font-weight:700;color:var(--error)">Clock Out</div>
                <div style="font-size:.72rem;color:var(--text-muted)">End shift</div>
              </span>
            </label>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('clockModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Submit</button>
      </div>
    </form>
  </div>
</div>

<!-- Schedule Shift Modal -->
<div class="modal-backdrop" id="scheduleModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Schedule a Shift</h3>
      <button class="modal-close" onclick="closeModal('scheduleModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="schedule">
      <div class="modal-body">
        <div class="form-group">
          <label>Staff Member</label>
          <select name="staff_id" class="form-control" required>
            <option value="">— Choose staff —</option>
            <?php foreach ($staff_list as $s): ?>
            <option value="<?php echo $s['id']; ?>"><?php echo htmlspecialchars($s['name']); ?> (<?php echo ucfirst($s['role']); ?>)</option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Shift Date</label>
          <input type="date" name="shift_date" class="form-control" value="<?php echo $view_date; ?>" required>
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label>Note (optional)</label>
          <textarea name="note" class="form-control" rows="2" placeholder="e.g. Morning shift, 8am–4pm"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('scheduleModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Schedule</button>
      </div>
    </form>
  </div>
</div>

<?php include("includes/footer.php"); ?>
