<?php
require_once 'vendor/autoload.php';
require_once 'config.php';

/**
 * Mobile-friendly SMS signup page
 */

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone'])) {
    $phone = $_POST['phone'];
    
    // Validate phone number
    if (!preg_match('/^\+?[0-9\s\-\(\)]{10,15}$/', $phone)) {
        $error = 'Please enter a valid phone number';
    } else {
        try {
            // Connect to database
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
            
            // Format phone number
            $numbersOnly = preg_replace('/[^0-9]/', '', $phone);
            if (strlen($numbersOnly) === 10) {
                $formattedPhone = '+1' . $numbersOnly;
            } elseif (strlen($numbersOnly) === 11 && substr($numbersOnly, 0, 1) === '1') {
                $formattedPhone = '+' . $numbersOnly;
            } else {
                $formattedPhone = '+' . $numbersOnly;
            }
            
            // Generate token
            $token = bin2hex(random_bytes(16));
            
            // Insert consent request
            $sql = "INSERT INTO consent_requests 
                    (phone_number, consent_token, consent_status, ip_address, user_agent)
                    VALUES (?, ?, 'pending', ?, ?)
                    ON DUPLICATE KEY UPDATE 
                    consent_token = VALUES(consent_token),
                    consent_status = 'pending',
                    request_date = CURRENT_TIMESTAMP";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$formattedPhone, $token, $_SERVER['REMOTE_ADDR'] ?? 'Signup', 'Mobile Signup']);
            
            // Generate consent URL (SMS links require absolute URLs)
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? "https" : "http") . "://" . ($_SERVER['HTTP_HOST'] ?? 'localhost');
            $scriptDir = dirname($_SERVER['PHP_SELF']);
            $pathPrefix = $scriptDir === '/' ? '' : rtrim($scriptDir, '/');
            $consentUrl = $baseUrl . $pathPrefix . "/consent_simple.php?token=" . urlencode($token) . "&phone=" . urlencode($formattedPhone);
            
            // Send SMS (when Twilio is verified)
            try {
                $twilio = new Twilio\Rest\Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
                
                $message = $twilio->messages->create(
                    $formattedPhone,
                    [
                        'from' => TWILIO_PHONE_NUMBER,
                        'body' => "Mark's Tech Solution: Please confirm SMS consent. Reply YES to approve or visit: " . $consentUrl . " Reply STOP to opt out."
                    ]
                );
                
                $success = "SMS sent! Check your phone and reply YES to confirm.";
                
                // Log the message
                $sql = "INSERT INTO message_logs 
                        (consent_id, phone_number, message_sid, message_content, message_type, status)
                        VALUES ((SELECT id FROM consent_requests WHERE consent_token = ?), ?, ?, ?, 'signup_request', 'sent')";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$token, $formattedPhone, $message->sid, "Signup SMS sent"]);
                
            } catch (Exception $e) {
                // If Twilio not verified, show the link instead
                $success = "Consent request created! Please visit this link to approve: <a href='$consentUrl'>$consentUrl</a>";
            }
            
        } catch (Exception $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Sign up for SMS updates from Mark's Tech Solution. Get service notifications, repair status updates, and appointment reminders for computer repair and IT support in East Weymouth, MA.">
    <meta name="keywords" content="SMS sign up, text alerts, Mark's Tech Solution, computer repair, IT support, appointment reminders, East Weymouth, MA">
    <meta name="author" content="Mark's Tech Solution">
    <meta name="robots" content="index, follow, max-image-preview:large">
    <meta name="theme-color" content="#ff6600">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <meta name="format-detection" content="telephone=yes">
    <title>SMS Sign Up - Mark's Tech Solution</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .mobile-container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
        }
        .phone-input {
            font-size: 18px;
            padding: 15px;
            border-radius: 10px;
            border: 2px solid #e0e0e0;
            text-align: center;
        }
        .phone-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        .signup-btn {
            width: 100%;
            padding: 15px;
            font-size: 18px;
            font-weight: bold;
            border-radius: 10px;
        }
        .success-message {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo h1 {
            font-size: 24px;
            margin: 0;
            color: #007bff;
        }
        .features {
            text-align: center;
            margin: 20px 0;
        }
        .features h5 {
            color: #666;
            font-size: 16px;
        }
        @media (max-width: 480px) {
            .mobile-container {
                padding: 10px;
            }
            .logo h1 {
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="mobile-container">
        <div class="logo">
            <h1>Mark's Tech Solution</h1>
        </div>
        
        <div class="features">
            <h5>Get SMS Updates & Alerts</h5>
            <p class="text-muted">Service updates • Support • Special offers</p>
        </div>
        
        <?php if ($success): ?>
            <div class="success-message">
                <h4>📱 Check Your Phone!</h4>
                <p><?php echo $success; ?></p>
                <small>You can close this window after confirming.</small>
            </div>
        <?php else: ?>
            <form method="POST">
                <div class="mb-3">
                    <label for="phone" class="form-label text-center d-block">Enter Your Phone Number</label>
                    <input type="tel" class="form-control phone-input" id="phone" name="phone" 
                           placeholder="(123) 456-7890" required>
                    <div class="form-text text-center">We'll send a confirmation SMS</div>
                </div>
                
                <button type="submit" class="btn btn-primary signup-btn">
                    📱 Sign Up for SMS Updates
                </button>
            </form>
            
            <div class="text-center mt-3">
                <small class="text-muted">
                    Message and data rates may apply. 
                    Reply STOP to unsubscribe at any time.
                </small>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger mt-3">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
        // Auto-close window after successful signup (mobile)
        <?php if ($success): ?>
        setTimeout(function() {
            if (window.history.length <= 2) {
                // If no history, try to close window
                window.close();
            }
        }, 5000);
        <?php endif; ?>
        
        // Format phone number as user types
        document.getElementById('phone').addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '';
            if (value.length >= 6) {
                value = value.slice(0, 3) + '-' + value.slice(3, 6) + '-' + value.slice(6, 10);
            } else if (value.length >= 3) {
                value = value.slice(0, 3) + '-' + value.slice(3);
            }
            e.target.value = value;
        });
    </script>
</body>
</html>
