<?php
/**
 * Quick Pick - Support Page
 * Professional support contact form for App Store
 * Sends SMS via Free Mobile API
 */

// Configuration
$config = [
    'app_name' => 'App Support',
    'company_name' => 'MJ B',
    'sms_user' => '96558250',
    'sms_pass' => '4UQkHw4k598T9Z',
    'recaptcha_site_key' => '6LfB_y8sAAAAAHCUHg9qDwAPKHuajqpce6_b4Uxz',
    'recaptcha_secret_key' => '6LfB_y8sAAAAAJ-FGtuplaZdiyHsvKsV6HyF15Bq',
];

// Handle form submission
$message_sent = false;
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $subject_type = trim($_POST['subject_type'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $device = trim($_POST['device'] ?? '');
    $app_version = trim($_POST['app_version'] ?? '');

    // Validation
    if (empty($name) || empty($email) || empty($message) || empty($device) || empty($app_version)) {
        $error_message = 'Please fill in all required fields.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Please enter a valid email address.';
    } else {
        // Verify reCAPTCHA
        $recaptcha_response = $_POST['g-recaptcha-response'] ?? '';
        $recaptcha_verify = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $config['recaptcha_secret_key'] . '&response=' . $recaptcha_response);
        $recaptcha_data = json_decode($recaptcha_verify);

        if (!$recaptcha_data->success) {
            $error_message = 'Please complete the reCAPTCHA verification.';
        } else {
            // Build SMS message (max 999 chars for Free Mobile)
            $sms_content = "[{$config['app_name']}]\n";
            $sms_content .= "Type: {$subject_type}\n";
            $sms_content .= "From: {$name}\n";
            $sms_content .= "Email: {$email}\n";
            if (!empty($device))
                $sms_content .= "Device: {$device}\n";
            if (!empty($app_version))
                $sms_content .= "Ver: {$app_version}\n";
            $sms_content .= "---\n";
            $sms_content .= substr($message, 0, 500); // Limit message length

            // Send SMS via Free Mobile API (POST with JSON)
            $api_url = 'https://smsapi.free-mobile.fr/sendmsg';

            $post_data = json_encode([
                'user' => $config['sms_user'],
                'pass' => $config['sms_pass'],
                'msg' => $sms_content
            ]);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curl_error = curl_error($ch);

            // Debug log - show everything in terminal
            error_log("=== SMS API DEBUG ===");
            error_log("URL: {$api_url}");
            error_log("POST Data: {$post_data}");
            error_log("HTTP Code: {$http_code}");
            error_log("Response: {$response}");
            error_log("cURL Error: {$curl_error}");
            error_log("=== END DEBUG ===");

            // Handle response
            switch ($http_code) {
                case 200:
                    $message_sent = true;
                    break;
                case 400:
                    $error_message = 'Configuration error. Please contact support directly.';
                    break;
                case 402:
                    $error_message = 'Too many messages sent. Please try again later.';
                    break;
                case 403:
                    $error_message = 'Service unavailable. Please try again later.';
                    break;
                case 500:
                    $error_message = 'Server error. Please try again later.';
                    break;
                default:
                    $error_message = "Failed to send message (Code: {$http_code}). Please try again.";
                    if (!empty($curl_error)) {
                        error_log("SMS API Error: " . $curl_error);
                    }
            }
        } // end reCAPTCHA else
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($config['app_name']) ?></title>
    <script
        src="https://www.google.com/recaptcha/api.js?render=<?= htmlspecialchars($config['recaptcha_site_key']) ?>"></script>
    <style>
        :root {
            --primary: #007AFF;
            --primary-dark: #0056CC;
            --bg: #F5F5F7;
            --card-bg: #FFFFFF;
            --text: #1D1D1F;
            --text-secondary: #86868B;
            --border: #D2D2D7;
            --success: #34C759;
            --error: #FF3B30;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', Roboto, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            min-height: 100vh;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .app-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #007AFF, #5856D6);
            border-radius: 18px;
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 20px rgba(0, 122, 255, 0.3);
        }

        .app-icon svg {
            width: 45px;
            height: 45px;
            fill: white;
        }

        h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .subtitle {
            color: var(--text-secondary);
            font-size: 16px;
        }

        .card {
            background: var(--card-bg);
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        }

        .form-group {
            margin-bottom: 24px;
        }

        label {
            display: block;
            font-weight: 500;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .required::after {
            content: ' *';
            color: var(--error);
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid var(--border);
            border-radius: 10px;
            font-size: 16px;
            font-family: inherit;
            transition: border-color 0.2s, box-shadow 0.2s;
            background: var(--card-bg);
        }

        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.15);
        }

        textarea {
            resize: vertical;
            min-height: 150px;
        }

        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        @media (max-width: 480px) {
            .row {
                grid-template-columns: 1fr;
            }
        }

        button {
            width: 100%;
            padding: 14px;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s, transform 0.1s;
        }

        button:hover {
            background: var(--primary-dark);
        }

        button:active {
            transform: scale(0.98);
        }

        .alert {
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 24px;
            font-size: 14px;
        }

        .alert-success {
            background: rgba(52, 199, 89, 0.1);
            color: var(--success);
            border: 1px solid rgba(52, 199, 89, 0.3);
        }

        .alert-error {
            background: rgba(255, 59, 48, 0.1);
            color: var(--error);
            border: 1px solid rgba(255, 59, 48, 0.3);
        }

        .footer {
            text-align: center;
            margin-top: 40px;
            color: var(--text-secondary);
            font-size: 13px;
        }

        .footer a {
            color: var(--primary);
            text-decoration: none;
        }

        .footer a:hover {
            text-decoration: underline;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <div class="app-icon">
                <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path
                        d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
                </svg>
            </div>
            <h1><?= htmlspecialchars($config['app_name']) ?></h1>
            <p class="subtitle">We're here to help. Send us a message.</p>
        </div>

        <div class="card">
            <?php if ($message_sent): ?>
                <div class="alert alert-success">
                    <strong>Message Sent!</strong><br>
                    Thank you for contacting us. We'll get back to you as soon as possible.
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="alert alert-error">
                    <?= htmlspecialchars($error_message) ?>
                </div>
            <?php endif; ?>

            <?php if (!$message_sent): ?>
                <form method="POST" action="">
                    <div class="form-group">
                        <label for="name" class="required">Your Name</label>
                        <input type="text" id="name" name="name" required
                            value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" placeholder="John Doe">
                    </div>

                    <div class="form-group">
                        <label for="email" class="required">Email Address</label>
                        <input type="email" id="email" name="email" required
                            value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" placeholder="you@example.com">
                    </div>

                    <div class="form-group">
                        <label for="subject_type">What can we help you with?</label>
                        <select id="subject_type" name="subject_type">
                            <option value="Question">General Question</option>
                            <option value="Bug Report">Bug Report</option>
                            <option value="Feature Request">Feature Request</option>
                            <option value="Purchase Issue">Purchase / Billing Issue</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>

                    <div class="row">
                        <div class="form-group">
                            <label for="device" class="required">Device</label>
                            <input type="text" id="device" name="device" required
                                value="<?= htmlspecialchars($_POST['device'] ?? '') ?>" placeholder="e.g. iPhone 15 Pro">
                        </div>

                        <div class="form-group">
                            <label for="app_version" class="required">App Version</label>
                            <input type="text" id="app_version" name="app_version" required
                                value="<?= htmlspecialchars($_POST['app_version'] ?? '') ?>" placeholder="e.g. 1.0.0">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="message" class="required">Message</label>
                        <textarea id="message" name="message" required
                            placeholder="Please describe your question or issue in detail..."><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
                    </div>

                    <input type="hidden" name="g-recaptcha-response" id="recaptchaResponse">

                    <button type="submit" id="submitBtn">Send Message</button>
                </form>
                <script>
                    grecaptcha.ready(function () {
                        document.getElementById('submitBtn').addEventListener('click', function (e) {
                            e.preventDefault();
                            grecaptcha.execute('<?= htmlspecialchars($config['recaptcha_site_key']) ?>', { action: 'submit' }).then(function (token) {
                                document.getElementById('recaptchaResponse').value = token;
                                document.querySelector('form').submit();
                            });
                        });
                    });
                </script>
            <?php else: ?>
                <a href="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>"
                    style="display: block; text-align: center; color: var(--primary); text-decoration: none; font-weight: 500;">Send
                    Another Message</a>
            <?php endif; ?>
        </div>

        <div class="footer">
            <p>&copy; <?= date('Y') ?> <?= htmlspecialchars($config['company_name']) ?>. All rights reserved.</p>
        </div>
    </div>
</body>

</html>