<?php
/**
 * Email Configuration Wizard
 * Setup email reminders and notifications for document signing
 */

session_start();

// Check if config.php exists
if (!file_exists('config.php')) {
    die('⚠️ Error: config.php not found. Run setup-complete.php first.');
}

require 'config.php';

$step = $_GET['step'] ?? 1;
$error = '';
$success = '';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Save email configuration
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_config'])) {
    $method = $_POST['method'] ?? 'disabled';
    $from_email = $_POST['from_email'] ?? '';
    $from_name = $_POST['from_name'] ?? '';
    $smtp_host = $_POST['smtp_host'] ?? '';
    $smtp_port = $_POST['smtp_port'] ?? '587';
    $smtp_user = $_POST['smtp_user'] ?? '';
    $smtp_pass = $_POST['smtp_pass'] ?? '';

    if ($method != 'disabled' && empty($from_email)) {
        $error = 'From email address is required';
    } else {
        // Update config.php
        $config_content = file_get_contents('config.php');

        $replacements = [
            "define('MAIL_METHOD'" => "define('MAIL_METHOD', '$method');define('MAIL_METHOD_OLD'",
            "define('MAIL_FROM_EMAIL'" => "define('MAIL_FROM_EMAIL', '$from_email');define('MAIL_FROM_EMAIL_OLD'",
            "define('MAIL_FROM_NAME'" => "define('MAIL_FROM_NAME', '$from_name');define('MAIL_FROM_NAME_OLD'",
            "define('SMTP_HOST'" => "define('SMTP_HOST', '$smtp_host');define('SMTP_HOST_OLD'",
            "define('SMTP_PORT'" => "define('SMTP_PORT', $smtp_port);define('SMTP_PORT_OLD'",
            "define('SMTP_USER'" => "define('SMTP_USER', '$smtp_user');define('SMTP_USER_OLD'",
            "define('SMTP_PASS'" => "define('SMTP_PASS', '$smtp_pass');define('SMTP_PASS_OLD'",
        ];

        // Add email settings to config if they don't exist
        if (strpos($config_content, "define('MAIL_METHOD'") === false) {
            $config_content = str_replace('<?php', "<?php\n// Email Configuration\ndefine('MAIL_METHOD', '$method');\ndefine('MAIL_FROM_EMAIL', '$from_email');\ndefine('MAIL_FROM_NAME', '$from_name');\ndefine('SMTP_HOST', '$smtp_host');\ndefine('SMTP_PORT', $smtp_port);\ndefine('SMTP_USER', '$smtp_user');\ndefine('SMTP_PASS', '$smtp_pass');\n", $config_content);
        } else {
            foreach ($replacements as $old => $new) {
                $config_content = preg_replace("/" . preg_quote($old, '/') . ".*?;/", $new . ";", $config_content);
            }
        }

        if (file_put_contents('config.php', $config_content)) {
            $success = '✅ Email configuration saved! Reminders are now ' . ($method == 'disabled' ? 'disabled' : 'enabled');
        } else {
            $error = 'Could not write to config.php. Check file permissions.';
        }
    }
}

// Get current settings
$mail_method = defined('MAIL_METHOD') ? MAIL_METHOD : 'disabled';
$mail_from_email = defined('MAIL_FROM_EMAIL') ? MAIL_FROM_EMAIL : '';
$mail_from_name = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : '';
$smtp_host = defined('SMTP_HOST') ? SMTP_HOST : '';
$smtp_port = defined('SMTP_PORT') ? SMTP_PORT : '587';
$smtp_user = defined('SMTP_USER') ? SMTP_USER : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Configuration</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f5f5; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; }
        .header h1 { font-size: 28px; margin-bottom: 10px; }
        .header p { opacity: 0.9; }
        .content { padding: 40px; }
        .tabs { display: flex; gap: 10px; margin-bottom: 30px; border-bottom: 2px solid #eee; }
        .tab-btn { padding: 12px 20px; background: none; border: none; cursor: pointer; font-size: 14px; font-weight: bold; color: #999; border-bottom: 3px solid transparent; transition: all 0.3s; }
        .tab-btn.active { color: #667eea; border-bottom-color: #667eea; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .alert { padding: 15px; margin-bottom: 20px; border-radius: 6px; }
        .alert.error { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
        .alert.success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        .info-box { background: #e7f3ff; padding: 20px; border-radius: 6px; border-left: 4px solid #2196F3; margin: 20px 0; }
        .info-box h3 { color: #1976D2; margin-bottom: 10px; }
        .info-box p { color: #555; line-height: 1.6; margin: 5px 0; }
        .info-box code { background: #fff; padding: 2px 6px; border-radius: 3px; font-family: monospace; color: #d63384; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #333; }
        .form-group input, .form-group select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; }
        .form-group input:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.1); }
        .form-hint { font-size: 12px; color: #999; margin-top: 5px; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .btn { padding: 12px 30px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; transition: all 0.3s; }
        .btn:hover { background: #5568d3; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(102,126,234,0.4); }
        .btn-secondary { background: #6c757d; }
        .btn-secondary:hover { background: #5a6268; }
        .status { padding: 15px; background: #f9f9f9; border-radius: 6px; margin: 20px 0; border-left: 4px solid #667eea; }
        .status-label { font-weight: bold; color: #333; }
        .status-value { color: #667eea; font-size: 16px; margin-top: 5px; }
        .method-select { display: grid; gap: 15px; margin: 20px 0; }
        .method-option { padding: 15px; border: 2px solid #ddd; border-radius: 6px; cursor: pointer; transition: all 0.3s; }
        .method-option input[type="radio"] { margin-right: 10px; }
        .method-option.selected { border-color: #667eea; background: #f0f4ff; }
        .instructions { background: #f9f9f9; padding: 20px; border-radius: 6px; margin: 20px 0; border-left: 4px solid #ff9800; }
        .instructions h3 { color: #e65100; margin-bottom: 10px; }
        .instructions ol { margin-left: 20px; line-height: 1.8; color: #555; }
        .test-btn { background: #28a745; }
        .test-btn:hover { background: #218838; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📧 Email Configuration</h1>
            <p>Setup reminders and notifications for unsigned documents</p>
        </div>

        <div class="content">
            <?php if ($error): ?><div class="alert error">❌ <?php echo htmlspecialchars($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert success">✅ <?php echo htmlspecialchars($success); ?></div><?php endif; ?>

            <div class="tabs">
                <button class="tab-btn <?php echo $step == 1 ? 'active' : ''; ?>" onclick="switchTab(1)">📋 Overview</button>
                <button class="tab-btn <?php echo $step == 2 ? 'active' : ''; ?>" onclick="switchTab(2)">⚙️ Configuration</button>
                <button class="tab-btn <?php echo $step == 3 ? 'active' : ''; ?>" onclick="switchTab(3)">📚 Instructions</button>
            </div>

            <!-- TAB 1: OVERVIEW -->
            <div class="tab-content <?php echo $step == 1 ? 'active' : ''; ?>">
                <h2>Email Reminders Overview</h2>

                <div class="info-box">
                    <h3>What This Does</h3>
                    <p>Automatically sends reminder emails to customers who haven't signed all their documents:</p>
                    <p>✓ First reminder: 24 hours after documents sent<br>
                    ✓ Follow-up reminders: Every 48 hours<br>
                    ✓ Reminder emails include document links<br>
                    ✓ Works for sales, finance docs, service agreements, etc.</p>
                </div>

                <div class="status">
                    <div class="status-label">Current Status:</div>
                    <div class="status-value">
                        <?php
                        if ($mail_method == 'disabled') {
                            echo '❌ Email reminders are DISABLED';
                        } else {
                            echo '✅ Email reminders are ENABLED (' . ucfirst($mail_method) . ')';
                        }
                        ?>
                    </div>
                </div>

                <div class="info-box">
                    <h3>Optional Feature</h3>
                    <p>Email is completely optional. Customers can:</p>
                    <p>✓ Sign documents via the customer portal (link stays active)<br>
                    ✓ Receive reminders manually<br>
                    ✓ Sign anytime without time pressure</p>
                    <p><strong>You don't need email to start using the system.</strong></p>
                </div>

                <p style="margin-top: 30px; color: #666;">
                    <strong>Ready to setup email?</strong> Go to the <strong>Configuration</strong> tab to choose your email method.
                </p>
            </div>

            <!-- TAB 2: CONFIGURATION -->
            <div class="tab-content <?php echo $step == 2 ? 'active' : ''; ?>">
                <h2>Email Configuration</h2>

                <form method="POST">
                    <div class="form-group">
                        <label>Email Method</label>
                        <div class="method-select">
                            <div class="method-option <?php echo $mail_method == 'disabled' ? 'selected' : ''; ?>">
                                <input type="radio" name="method" value="disabled" <?php echo $mail_method == 'disabled' ? 'checked' : ''; ?> onchange="updateMethodUI()">
                                <strong>Disabled (No Email)</strong>
                                <p style="font-size: 12px; color: #999; margin-top: 5px;">Don't send reminders - documents stay available via portal</p>
                            </div>

                            <div class="method-option <?php echo $mail_method == 'php_mail' ? 'selected' : ''; ?>">
                                <input type="radio" name="method" value="php_mail" <?php echo $mail_method == 'php_mail' ? 'checked' : ''; ?> onchange="updateMethodUI()">
                                <strong>PHP Mail Function</strong>
                                <p style="font-size: 12px; color: #999; margin-top: 5px;">Uses server's built-in email (simplest, no extra setup)</p>
                            </div>

                            <div class="method-option <?php echo $mail_method == 'smtp' ? 'selected' : ''; ?>">
                                <input type="radio" name="method" value="smtp" <?php echo $mail_method == 'smtp' ? 'checked' : ''; ?> onchange="updateMethodUI()">
                                <strong>SMTP (Gmail, Office 365, Custom)</strong>
                                <p style="font-size: 12px; color: #999; margin-top: 5px;">More reliable, requires email account credentials</p>
                            </div>
                        </div>
                    </div>

                    <div id="email-fields">
                        <div class="form-group">
                            <label>From Email Address</label>
                            <input type="email" name="from_email" value="<?php echo htmlspecialchars($mail_from_email); ?>" placeholder="noreply@garage.com" required>
                            <div class="form-hint">Email address that reminders will be sent from</div>
                        </div>

                        <div class="form-group">
                            <label>From Name</label>
                            <input type="text" name="from_name" value="<?php echo htmlspecialchars($mail_from_name); ?>" placeholder="Your Garage Name" required>
                            <div class="form-hint">Company/garage name that appears in emails</div>
                        </div>

                        <div id="smtp-fields" style="display: <?php echo $mail_method == 'smtp' ? 'block' : 'none'; ?>;">
                            <h3 style="margin: 30px 0 15px 0;">SMTP Settings</h3>

                            <div class="form-group">
                                <label>SMTP Server</label>
                                <input type="text" name="smtp_host" value="<?php echo htmlspecialchars($smtp_host); ?>" placeholder="smtp.gmail.com or smtp.office365.com">
                                <div class="form-hint">Your email provider's SMTP server</div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label>SMTP Port</label>
                                    <input type="number" name="smtp_port" value="<?php echo $smtp_port; ?>" placeholder="587">
                                    <div class="form-hint">Usually 587 (TLS) or 465 (SSL)</div>
                                </div>

                                <div class="form-group">
                                    <label>SMTP Username</label>
                                    <input type="email" name="smtp_user" value="<?php echo htmlspecialchars($smtp_user); ?>" placeholder="your-email@gmail.com">
                                    <div class="form-hint">Your email account</div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>SMTP Password</label>
                                <input type="password" name="smtp_pass" placeholder="Your password or app password">
                                <div class="form-hint">For Gmail: Use App Password, not regular password</div>
                            </div>
                        </div>
                    </div>

                    <div style="margin-top: 30px;">
                        <button type="submit" name="save_config" class="btn">💾 Save Configuration</button>
                    </div>
                </form>
            </div>

            <!-- TAB 3: INSTRUCTIONS -->
            <div class="tab-content <?php echo $step == 3 ? 'active' : ''; ?>">
                <h2>Setup Instructions</h2>

                <div class="instructions">
                    <h3>Option 1: PHP Mail (Recommended for Beginners)</h3>
                    <ol>
                        <li>Go to <strong>Configuration</strong> tab</li>
                        <li>Select <strong>"PHP Mail Function"</strong></li>
                        <li>Enter "From Email" (e.g., noreply@garage.com)</li>
                        <li>Enter "From Name" (your garage name)</li>
                        <li>Click <strong>Save Configuration</strong></li>
                        <li>Done! Reminders will be sent automatically</li>
                    </ol>
                </div>

                <div class="instructions">
                    <h3>Option 2: Gmail</h3>
                    <ol>
                        <li>Go to <strong>Configuration</strong> tab</li>
                        <li>Select <strong>"SMTP"</strong></li>
                        <li>Fill in these fields:
                            <ul style="margin: 10px 0 10px 20px;">
                                <li>SMTP Server: <code>smtp.gmail.com</code></li>
                                <li>SMTP Port: <code>587</code></li>
                                <li>SMTP Username: <code>your-gmail@gmail.com</code></li>
                                <li>SMTP Password: App password (see below)</li>
                            </ul>
                        </li>
                        <li><strong>Get Gmail App Password:</strong>
                            <ul style="margin: 10px 0 10px 20px;">
                                <li>Go to <a href="https://myaccount.google.com/security" target="_blank">Google Account Security</a></li>
                                <li>Enable 2-Step Verification (if not already)</li>
                                <li>Go to App Passwords (at bottom of security page)</li>
                                <li>Create new app password for "Mail" on "Windows/Linux"</li>
                                <li>Copy the 16-character password</li>
                            </ul>
                        </li>
                        <li>Paste the app password in "SMTP Password" field</li>
                        <li>Click <strong>Save Configuration</strong></li>
                    </ol>
                </div>

                <div class="instructions">
                    <h3>Option 3: Office 365 / Outlook</h3>
                    <ol>
                        <li>Go to <strong>Configuration</strong> tab</li>
                        <li>Select <strong>"SMTP"</strong></li>
                        <li>Fill in these fields:
                            <ul style="margin: 10px 0 10px 20px;">
                                <li>SMTP Server: <code>smtp.office365.com</code></li>
                                <li>SMTP Port: <code>587</code></li>
                                <li>SMTP Username: <code>your-email@company.com</code></li>
                                <li>SMTP Password: Your Office 365 password</li>
                            </ul>
                        </li>
                        <li>Click <strong>Save Configuration</strong></li>
                    </ol>
                </div>

                <div class="info-box">
                    <h3>Need Help?</h3>
                    <p><strong>Email not working?</strong></p>
                    <p>✓ Check that "From Email" is a valid email address<br>
                    ✓ For Gmail, make sure you're using App Password, not regular password<br>
                    ✓ Check SMTP Server and Port are correct<br>
                    ✓ Test with PHP Mail first (simpler)</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        function switchTab(num) {
            document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            document.querySelectorAll('.tab-btn')[num-1].classList.add('active');
            document.querySelectorAll('.tab-content')[num-1].classList.add('active');
            window.history.replaceState({}, '', '?step=' + num);
        }

        function updateMethodUI() {
            const method = document.querySelector('input[name="method"]:checked').value;
            const emailFields = document.getElementById('email-fields');
            const smtpFields = document.getElementById('smtp-fields');

            if (method == 'disabled') {
                emailFields.style.display = 'none';
            } else {
                emailFields.style.display = 'block';
                smtpFields.style.display = method == 'smtp' ? 'block' : 'none';
            }

            document.querySelectorAll('.method-option').forEach(el => el.classList.remove('selected'));
            document.querySelector(`input[value="${method}"]`).closest('.method-option').classList.add('selected');
        }

        // Initialize on load
        updateMethodUI();
    </script>
</body>
</html>
