<?php
require_once __DIR__ . '/../../api/lib.php';
hw_require_auth(['coach']);
$authUser = hw_get_auth_user();

$db = hw_db();
$coachStmt = $db->prepare("SELECT * FROM coaches WHERE user_id = ?");
$coachStmt->execute([$authUser['id']]);
$coach = $coachStmt->fetch(PDO::FETCH_ASSOC);

if (!$coach) {
    echo '<div class="p-8 text-center"><p class="text-red-600">Coach profile not found.</p></div>';
    exit;
}

$page_title = 'Schedule Management | Coach Dashboard';
$page_description = 'Set your availability and manage your coaching schedule';
$page_content = function () use ($authUser, $coach) {
?>
<style>
  nav.fixed { 
    display: none !important; 
    visibility: hidden !important;
    position: absolute !important;
    pointer-events: none !important;
    z-index: -1 !important;
  }
  body > nav { 
    display: none !important; 
    visibility: hidden !important;
  }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/atasteofafricanmarketplace/assets/dashboard.css">

<div class="dashboard-container">
  <!-- Sidebar -->
  <div class="dashboard-sidebar">
    <div class="sidebar-header">
      <div class="sidebar-profile">
        <div class="profile-avatar" style="background: linear-gradient(135deg, #10b981, #059669);">
          <?= strtoupper(substr($coach['display_name'], 0, 2)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($coach['display_name']) ?></h3>
          <p>Coach Portal</p>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/atasteofafricanmarketplace/dashboard/coach/index.php"><i class="fas fa-home"></i>Overview</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php"><i class="fas fa-calendar-check"></i>Sessions</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/clients.php"><i class="fas fa-users"></i>Clients</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/earnings.php"><i class="fas fa-dollar-sign"></i>Earnings</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/schedule.php" class="active"><i class="fas fa-clock"></i>Schedule</a>
      <hr class="sidebar-divider">
      <a href="/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/atasteofafricanmarketplace/api/auth/logout.php" style="display: flex; align-items: center; gap: 12px; color: rgba(255,255,255,0.7); text-decoration: none; font-size: 13px; font-weight: 500; padding: 10px 0; border-top: 1px solid rgba(212, 173, 49, 0.15); transition: all 0.3s;"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <!-- Header -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; flex-wrap: wrap; gap: 16px;">
        <div>
          <h1 style="font-size: 32px; font-weight: 800; color: #0b3d2e; margin: 0 0 8px 0;">Schedule Management</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">Set your availability and manage your coaching schedule</p>
        </div>
      </div>

      <!-- Schedule Grid -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 24px; margin-bottom: 32px;">
        <!-- Availability Settings -->
        <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; gap: 12px;">
            <i class="fas fa-cog" style="color: #10b981;"></i>
            Availability Settings
          </h3>
          
          <div style="display: flex; flex-direction: column; gap: 24px;">
            <!-- Timezone -->
            <div>
              <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">
                <i class="fas fa-globe" style="color: #10b981; margin-right: 6px;"></i>Time Zone
              </label>
              <select id="timezone" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit; background: white;">
                <option value="America/New_York">Eastern Time (EST)</option>
                <option value="America/Chicago">Central Time (CST)</option>
                <option value="America/Denver">Mountain Time (MST)</option>
                <option value="America/Los_Angeles">Pacific Time (PST)</option>
              </select>
            </div>

            <!-- Work Hours -->
            <div style="padding-top: 16px; border-top: 1px solid #e5e7eb;">
              <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 12px; font-size: 14px;">
                <i class="fas fa-clock" style="color: #10b981; margin-right: 6px;"></i>Work Hours
              </label>
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                <div>
                  <label style="display: block; font-size: 12px; color: #64748b; margin-bottom: 6px; font-weight: 600; text-transform: uppercase;">Start Time</label>
                  <input type="time" id="start-time" value="09:00" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
                </div>
                <div>
                  <label style="display: block; font-size: 12px; color: #64748b; margin-bottom: 6px; font-weight: 600; text-transform: uppercase;">End Time</label>
                  <input type="time" id="end-time" value="17:00" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
                </div>
              </div>
            </div>

            <!-- Working Days -->
            <div style="padding-top: 16px; border-top: 1px solid #e5e7eb;">
              <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 12px; font-size: 14px;">
                <i class="fas fa-calendar-week" style="color: #10b981; margin-right: 6px;"></i>Working Days
              </label>
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Sunday" style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Sunday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Monday" checked style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Monday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Tuesday" checked style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Tuesday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Wednesday" checked style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Wednesday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Thursday" checked style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Thursday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Friday" checked style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Friday</span>
                </label>
                <label style="display: flex; align-items: center; padding: 10px 12px; background: #f9fafb; border-radius: 8px; cursor: pointer; transition: all 0.3s;" onmouseover="this.style.background='#f0f9f6'" onmouseout="this.style.background='#f9fafb'">
                  <input type="checkbox" class="day-checkbox" value="Saturday" style="width: 18px; height: 18px; accent-color: #10b981; cursor: pointer;">
                  <span style="margin-left: 10px; font-size: 14px; color: #0b3d2e; font-weight: 500;">Saturday</span>
                </label>
              </div>
            </div>

            <!-- Info Box -->
            <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 16px; border-radius: 12px; border: 1px solid #d4ad31;">
              <p style="margin: 0; font-size: 13px; color: #64748b; display: flex; align-items: start; gap: 10px;">
                <i class="fas fa-info-circle" style="color: #10b981; font-size: 16px; flex-shrink: 0; margin-top: 2px;"></i>
                <span>Your availability will be displayed to clients when they book sessions. Make sure to keep your schedule updated.</span>
              </p>
            </div>

            <!-- Save Button -->
            <button onclick="saveSchedule()" style="width: 100%; background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 14px; border-radius: 10px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); display: flex; align-items: center; justify-content: center; gap: 8px;">
              <i class="fas fa-save"></i> Save Availability
            </button>
          </div>
        </div>

        <!-- Calendar View -->
        <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; gap: 12px;">
            <i class="fas fa-calendar-alt" style="color: #10b981;"></i>
            This Week's Schedule
          </h3>
          
          <div id="weekly-schedule" style="display: flex; flex-direction: column; gap: 12px;">
            <div style="display: flex; align-items: center; justify-center; padding: 60px 20px; background: #f9fafb; border-radius: 12px;">
              <div style="text-align: center;">
                <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #10b981; margin-bottom: 16px;"></i>
                <p style="color: #64748b; margin: 0; font-size: 14px;">Loading schedule...</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Upcoming Sessions -->
      <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; gap: 12px;">
          <i class="fas fa-calendar-check" style="color: #10b981;"></i>
          Upcoming Sessions
        </h3>
        <div id="upcoming-sessions" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px;">
          <div style="display: flex; align-items: center; justify-center; padding: 40px; grid-column: 1 / -1;">
            <div style="text-align: center;">
              <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #10b981; margin-bottom: 16px;"></i>
              <p style="color: #64748b; margin: 0; font-size: 14px;">Loading sessions...</p>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<style>
button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2) !important;
}

button:active {
  transform: translateY(0);
}

input:focus, select:focus {
  outline: none;
  border-color: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}
</style>

<script>
const coachId = <?= $coach['id'] ?>;

// Load weekly schedule
async function loadWeeklySchedule() {
    try {
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - startDate.getDay() + 1);
        
        const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
        const html = days.map((day, index) => {
            const date = new Date(startDate);
            date.setDate(date.getDate() + index);
            const isToday = date.toDateString() === new Date().toDateString();
            
            return `
                <div style="background: ${isToday ? 'linear-gradient(135deg, #f0f9f6, #e0f2fe)' : '#f9fafb'}; padding: 16px; border-radius: 12px; border: 2px solid ${isToday ? '#10b981' : '#e5e7eb'}; transition: all 0.3s;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <div>
                            <div style="font-weight: 700; color: #0b3d2e; font-size: 15px;">${day}</div>
                            <div style="font-size: 13px; color: #64748b;">${date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</div>
                        </div>
                        ${isToday ? '<span style="background: #10b981; color: white; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 700;">TODAY</span>' : ''}
                    </div>
                    <div style="font-size: 13px; color: #64748b; display: flex; align-items: center; gap: 8px;">
                        <i class="fas fa-clock" style="color: #10b981;"></i>
                        <span>Available</span>
                    </div>
                </div>
            `;
        }).join('');
        
        document.getElementById('weekly-schedule').innerHTML = html;
    } catch (error) {
        console.error('Error loading schedule:', error);
        document.getElementById('weekly-schedule').innerHTML = 
            '<p style="text-align: center; color: #ef4444; padding: 40px;">Error loading schedule</p>';
    }
}

// Load upcoming sessions
async function loadUpcomingSessions() {
    try {
        const response = await fetch('/atasteofafricanmarketplace/api/appointments/list.php?limit=10&coach_id=' + coachId);
        const data = await response.json();
        
        if (!data.success) {
            document.getElementById('upcoming-sessions').innerHTML = 
                '<div style="grid-column: 1 / -1; text-align: center; padding: 40px; background: #f9fafb; border-radius: 12px;"><p style="color: #64748b; margin: 0;">No upcoming sessions</p></div>';
            return;
        }

        const sessions = data.appointments || [];
        if (!sessions.length) {
            document.getElementById('upcoming-sessions').innerHTML = 
                '<div style="grid-column: 1 / -1; text-align: center; padding: 40px; background: #f9fafb; border-radius: 12px;"><i class="fas fa-calendar-times" style="font-size: 48px; color: #cbd5e1; margin-bottom: 16px;"></i><p style="color: #64748b; margin: 0;">No upcoming sessions scheduled</p></div>';
            return;
        }

        const html = sessions.map(session => {
            const startDate = new Date(session.starts_at);
            const dateStr = startDate.toLocaleDateString('en-US', { 
                weekday: 'short', 
                month: 'short', 
                day: 'numeric' 
            });
            const timeStr = startDate.toLocaleTimeString('en-US', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
            
            const statusColors = {
                'scheduled': { bg: '#dbeafe', text: '#1e40af' },
                'completed': { bg: '#d1fae5', text: '#065f46' },
                'cancelled': { bg: '#f3f4f6', text: '#4b5563' }
            };
            const status = statusColors[session.status] || statusColors['scheduled'];
            
            return `
                <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 20px; border-radius: 12px; border: 2px solid #e5e7eb; transition: all 0.3s;" onmouseover="this.style.borderColor='#10b981'; this.style.boxShadow='0 4px 12px rgba(16, 185, 129, 0.2)'" onmouseout="this.style.borderColor='#e5e7eb'; this.style.boxShadow='none'">
                    <div style="display: flex; justify-content: between; align-items: start; gap: 12px; margin-bottom: 12px;">
                        <div style="width: 48px; height: 48px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 16px; flex-shrink: 0;">
                            <i class="fas fa-video"></i>
                        </div>
                        <div style="flex: 1;">
                            <h4 style="font-size: 16px; font-weight: 700; color: #0b3d2e; margin: 0 0 6px 0;">${session.client_name || 'Session'}</h4>
                            <div style="font-size: 13px; color: #64748b; display: flex; flex-direction: column; gap: 4px;">
                                <span><i class="far fa-calendar" style="color: #10b981; width: 16px;"></i> ${dateStr}</span>
                                <span><i class="far fa-clock" style="color: #10b981; width: 16px;"></i> ${timeStr}</span>
                                <span><i class="fas fa-hourglass-half" style="color: #10b981; width: 16px;"></i> ${session.duration || 60} min</span>
                            </div>
                        </div>
                    </div>
                    <div style="background: ${status.bg}; color: ${status.text}; padding: 6px 12px; border-radius: 8px; font-size: 11px; font-weight: 700; text-transform: uppercase; text-align: center;">
                        ${session.status || 'Scheduled'}
                    </div>
                </div>
            `;
        }).join('');
        
        document.getElementById('upcoming-sessions').innerHTML = html;
    } catch (error) {
        console.error('Error loading sessions:', error);
        document.getElementById('upcoming-sessions').innerHTML = 
            '<div style="grid-column: 1 / -1; text-align: center; padding: 40px;"><p style="color: #ef4444;">Error loading sessions</p></div>';
    }
}

// Save schedule
async function saveSchedule() {
    const timezone = document.getElementById('timezone').value;
    const startTime = document.getElementById('start-time').value;
    const endTime = document.getElementById('end-time').value;
    const workingDays = Array.from(document.querySelectorAll('.day-checkbox:checked'))
        .map(cb => cb.value);

    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

    try {
        const response = await fetch('/atasteofafricanmarketplace/api/coaches/availability.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify({
                timezone,
                start_time: startTime,
                end_time: endTime,
                working_days: workingDays
            })
        });

        const data = await response.json();
        if (data.success) {
            alert('✓ Schedule saved successfully!');
            loadWeeklySchedule();
        } else {
            alert('Error saving schedule: ' + (data.error || data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error saving schedule. Please try again.');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-save"></i> Save Availability';
    }
}

// Initialize
window.addEventListener('DOMContentLoaded', () => {
    loadWeeklySchedule();
    loadUpcomingSessions();
});
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
