<?php
require_once __DIR__ . '/_site_content.php';
require_once __DIR__ . '/../config/database.php';

$db = Database::getInstance();
$user = getCurrentUser();

$name = '';
$email = '';
$phone = '';
$topic = '';
$details = '';
$preferredRaw = '';
$timezone = date_default_timezone_get();
$errors = [];
$successMessage = null;

$durationOptions = [15, 30, 60];
$availableCurrencies = ['GHS', 'USD', 'EUR'];
$selectedDuration = 15;
$selectedCurrency = 'GHS';

$eurRate = 1.0;
try {
    $rateRow = $db->get("SELECT setting_value FROM system_settings WHERE setting_key = 'currency_eur_rate' LIMIT 1");
    if ($rateRow && isset($rateRow['setting_value']) && is_numeric($rateRow['setting_value'])) {
        $eurRate = (float)$rateRow['setting_value'];
    }
} catch (Exception $e) {
    $eurRate = 1.0;
}

if ($user) {
    $name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
    $email = $user['email'] ?? '';
    $phone = $user['phone'] ?? '';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $topic = trim($_POST['topic'] ?? '');
    $details = trim($_POST['details'] ?? '');
    $preferredRaw = trim($_POST['preferred_datetime'] ?? '');
    $timezone = trim($_POST['timezone'] ?? date_default_timezone_get());
    $selectedDuration = (int)($_POST['duration_minutes'] ?? 15);
    $selectedCurrency = strtoupper(trim($_POST['currency'] ?? 'GHS'));

    if ($name === '') {
        $errors[] = 'Name is required.';
    }
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'A valid email address is required.';
    }
    if ($topic === '') {
        $errors[] = 'Please provide a short topic or reason for the appointment.';
    }

    $preferredDateTime = null;
    if ($preferredRaw !== '') {
        $ts = strtotime($preferredRaw);
        if ($ts === false) {
            $errors[] = 'Preferred date and time is invalid.';
        } else {
            $preferredDateTime = date('Y-m-d H:i:s', $ts);
        }
    }

    if (!in_array($selectedDuration, $durationOptions, true)) {
        $errors[] = 'Please select a valid appointment duration.';
    }
    if (!in_array($selectedCurrency, $availableCurrencies, true)) {
        $errors[] = 'Please select a valid currency.';
    }

    if (empty($errors)) {
        $userId = getCurrentUserId();

        $amount = 0.0;
        if ($selectedDuration === 30) {
            if ($selectedCurrency === 'GHS') {
                $amount = 1500.0;
            } elseif ($selectedCurrency === 'USD') {
                $amount = 100.0;
            } elseif ($selectedCurrency === 'EUR') {
                $amount = 100.0 * $eurRate;
            }
        } elseif ($selectedDuration === 60) {
            if ($selectedCurrency === 'GHS') {
                $amount = 2000.0;
            } elseif ($selectedCurrency === 'USD') {
                $amount = 150.0;
            } elseif ($selectedCurrency === 'EUR') {
                $amount = 150.0 * $eurRate;
            }
        }

        $paymentStatus = $amount > 0 ? 'pending' : 'free';

        $appointmentId = $db->insert('appointments', [
            'user_id' => $userId ?: null,
            'name' => $name,
            'email' => $email,
            'phone' => $phone ?: null,
            'topic' => $topic,
            'details' => $details ?: null,
            'preferred_datetime' => $preferredDateTime,
            'timezone' => $timezone ?: null,
            'duration_minutes' => $selectedDuration,
            'amount' => $amount,
            'currency' => $selectedCurrency,
            'payment_status' => $paymentStatus,
            'status' => 'requested',
            'created_at' => formatDate(),
        ]);

        if ($appointmentId) {
            if (function_exists('sendAppointmentRequestNotifications')) {
                sendAppointmentRequestNotifications((int)$appointmentId);
            }
            $successMessage = 'Your appointment request has been submitted. We will email you with the Zoom details once it is scheduled.';
            // Clear form values after success
            $topic = '';
            $details = '';
            $preferredRaw = '';
            $selectedDuration = 15;
            $selectedCurrency = 'GHS';
        } else {
            $errors[] = 'We could not save your appointment request. Please try again later.';
        }
    }
}

$baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Schedule an Appointment - SmartThink</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/modern-ux.css">
    <link rel="stylesheet" href="../assets/css/capgemini-theme.css">
    <link rel="stylesheet" href="../assets/css/page-styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800,900&display=swap" rel="stylesheet">

    <style>
        main { padding-top: 140px; padding-bottom: 80px; }
        .appointment-card { max-width: 720px; margin: 0 auto; }
    </style>
</head>
<body>
    <div class="scroll-progress" id="scrollProgress"></div>

    <div class="utility-bar">
        <div class="container">
            <div class="utility-links">
                <a href="mailto:study@smartthinkllc.com"><i class="fas fa-envelope"></i><span>study@smartthinkllc.com</span></a>
                <a href="tel:+12027907745"><i class="fas fa-phone"></i><span>(+1) 202-790-7745</span></a>
            </div>
            <div class="utility-right">
                <div class="utility-item">
                    <i class="fas fa-search"></i>
                    <span>Search</span>
                </div>
                <div class="theme-toggle" onclick="toggleTheme()">
                    <i class="fas fa-moon" id="themeIcon"></i>
                </div>
            </div>
        </div>
    </div>

    <header class="cap-header">
        <div class="container">
            <a class="cap-brand" href="index.php">
                <img src="../assets/images/logo.jpeg" alt="SmartThink" class="cap-logo">
                <span class="cap-brand-text">SmartThink</span>
            </a>

            <nav>
                <ul class="cap-nav">
                    <li class="cap-nav-item"><a class="cap-nav-link" href="about.php">About us</a></li>
                    <li class="cap-nav-item has-dropdown">
                        <a class="cap-nav-link" href="services.php">
                            Services
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="cap-dropdown">
                            <a class="cap-dropdown-link" href="advisory_it_solutions.php">Advisory and IT Solutions</a>
                            <a class="cap-dropdown-link" href="training.php">Training</a>
                            <a class="cap-dropdown-link" href="recruitment.php">Recruitment</a>
                        </div>
                    </li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="courses.php">Courses</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="careers.php">Careers</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link" href="news.php">News</a></li>
                    <li class="cap-nav-item"><a class="cap-nav-link active" href="appointment.php">Appointment</a></li>
                </ul>
            </nav>

            <div class="d-flex align-items-center">
                <div class="cap-auth ms-4">
                    <a href="../lms/login.php" class="btn-cap-login">Login</a>
                    <a href="../lms/register.php" class="btn-cap-register">Register</a>
                </div>
                <button class="navbar-toggler d-lg-none ms-3" type="button" style="background: transparent; border: none; color: white;" onclick="document.querySelector('.cap-nav').classList.toggle('open')">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </header>

    <main>
        <div class="container">
            <div class="appointment-card card">
                <div class="card-header">
                    <h1 class="h4 mb-0">Schedule an Appointment</h1>
                    <p class="text-muted mb-0">Book a time to meet with SmartThink via Zoom.</p>
                </div>
                <div class="card-body">
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $err): ?>
                                    <li><?php echo htmlspecialchars($err); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <?php if ($successMessage): ?>
                        <div class="alert alert-success">
                            <?php echo htmlspecialchars($successMessage); ?>
                        </div>
                    <?php endif; ?>

                    <form method="post" novalidate>
                        <div class="mb-3">
                            <label class="form-label">Full Name<span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($name); ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Email<span class="text-danger">*</span></label>
                            <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($email); ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($phone); ?>" placeholder="Optional">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Appointment Topic<span class="text-danger">*</span></label>
                            <input type="text" name="topic" class="form-control" value="<?php echo htmlspecialchars($topic); ?>" placeholder="e.g. Course guidance, Corporate training, Career mentoring" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Details</label>
                            <textarea name="details" class="form-control" rows="4" placeholder="Share any details that will help us prepare for your appointment."><?php echo htmlspecialchars($details); ?></textarea>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-7">
                                <label class="form-label">Appointment Type<span class="text-danger">*</span></label>
                                <select name="duration_minutes" class="form-select" required>
                                    <option value="15" <?php echo $selectedDuration === 15 ? 'selected' : ''; ?>>15 minutes - Introductory session (Free)</option>
                                    <option value="30" <?php echo $selectedDuration === 30 ? 'selected' : ''; ?>>30 minutes - Standard session (Paid)</option>
                                    <option value="60" <?php echo $selectedDuration === 60 ? 'selected' : ''; ?>>60 minutes - Deep-dive session (Paid)</option>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label">Currency<span class="text-danger">*</span></label>
                                <select name="currency" class="form-select" required>
                                    <option value="GHS" <?php echo $selectedCurrency === 'GHS' ? 'selected' : ''; ?>>GHS (Ghana Cedi)</option>
                                    <option value="USD" <?php echo $selectedCurrency === 'USD' ? 'selected' : ''; ?>>USD (US Dollar)</option>
                                    <option value="EUR" <?php echo $selectedCurrency === 'EUR' ? 'selected' : ''; ?>>EUR (Euro)</option>
                                </select>
                            </div>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-7">
                                <label class="form-label">Preferred Date &amp; Time</label>
                                <input type="datetime-local" name="preferred_datetime" class="form-control" value="<?php echo $preferredRaw !== '' ? htmlspecialchars($preferredRaw) : ''; ?>">
                            </div>
                            <div class="col-md-5">
                                <label class="form-label">Time zone</label>
                                <input type="text" name="timezone" class="form-control" value="<?php echo htmlspecialchars($timezone); ?>" placeholder="e.g. UTC, Africa/Accra">
                            </div>
                        </div>

                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-calendar-check me-2"></i>Submit Request
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/main.js"></script>
</body>
</html>
