<?php
require_once 'config.php';
require_once __DIR__ . '/../includes/security.php';

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $securityCheck = validateFormSubmission('pestcure_register_form', true);
    if (!$securityCheck['valid']) {
        $error = $securityCheck['error'];
    } else {
        $company = sanitizeString($_POST['company_name'] ?? '', 100);
        $contact = sanitizeString($_POST['contact_person'] ?? '', 100);
        $email = sanitizeEmail($_POST['email'] ?? '');
        $phone = sanitizePhone($_POST['phone'] ?? '');
        $location = sanitizeString($_POST['location'] ?? '', 100);
        $business_type = sanitizeString($_POST['business_type'] ?? '', 50);
        $message = sanitizeString($_POST['message'] ?? '', 1000);
        $password = $_POST['password'] ?? '';
        $password_confirm = $_POST['password_confirm'] ?? '';

        if (empty($company) || empty($contact) || empty($email) || empty($phone) || empty($password)) {
            $error = 'Please fill in all required fields.';
        } elseif ($email === false) {
            $error = 'Please enter a valid email address.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $password_confirm) {
            $error = 'Passwords do not match.';
        } else {
            try {
                $db = getDB();
                $stmt = $db->prepare('SELECT id, is_active FROM users WHERE email = ? OR username = ?');
                $stmt->execute([$email, $email]);
                $existing = $stmt->fetch();

                if ($existing) {
                    if ($existing['is_active']) {
                        $error = 'An account with this email already exists. Please login instead.';
                    } else {
                        $error = 'An application with this email is pending approval.';
                    }
                } else {
                    $token = bin2hex(random_bytes(32));
                    $passwordHash = password_hash($password, PASSWORD_DEFAULT);

                    $stmt = $db->prepare('INSERT INTO users (username, password, email, company_name, contact_person, phone, location, business_type, role, is_active, approval_token) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)');
                    $stmt->execute([$email, $passwordHash, $email, $company, $contact, $phone, $location, $business_type, 'reseller', $token]);

                    $approveUrl = SITE_URL . '/reseller/approve.php?token=' . $token;
                    $to = 'cois@pestcure.co.za';
                    $subject = "New Reseller Application - {$company}";
                    $emailBody = "
Pestcure - NEW RESELLER APPLICATION
========================================

Company: {$company}
Contact: {$contact}
Email: {$email}
Phone: {$phone}
Location: {$location}
Business Type: {$business_type}

Message:
{$message}

To APPROVE: {$approveUrl}

Submitted: " . date('d M Y, H:i') . "
";
                    $headers = "From: Pestcure <noreply@pestcure.co.za>\r\n";
                    $headers .= "Reply-To: {$email}\r\n";
                    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
                    mail($to, $subject, $emailBody, $headers);
                    $success = true;
                }
            } catch (PDOException $e) {
                $error = 'Registration failed. Please try again later.';
                error_log('Registration error: ' . $e->getMessage());
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Become a Reseller - Pestcure</title>
    <link rel="icon" type="image/x-icon" href="../favicon.ico">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 40px 20px; }
        .register-container { background: white; padding: 40px; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); width: 100%; max-width: 500px; }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo img { height: 60px; }
        .logo h1 { font-size: 1.5rem; color: #333; margin-top: 10px; }
        .logo p { color: #666; font-size: 14px; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .form-group { margin-bottom: 18px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; font-size: 14px; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; font-family: inherit; }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #ea580c; }
        .form-group textarea { resize: vertical; min-height: 80px; }
        .form-group small { color: #999; font-size: 12px; }
        .btn { width: 100%; padding: 14px; background: #ea580c; color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; }
        .btn:hover { opacity: 0.9; transform: translateY(-2px); }
        .error { background: #fee; color: #c00; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; }
        .success-message { text-align: center; padding: 40px 20px; }
        .success-message .icon { width: 80px; height: 80px; background: #e8f5e9; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; font-size: 40px; }
        .success-message h2 { color: #2e7d32; margin-bottom: 10px; }
        .success-message p { color: #666; margin-bottom: 24px; line-height: 1.6; }
        .back-link { text-align: center; margin-top: 20px; }
        .back-link a { color: #666; text-decoration: none; font-size: 14px; }
        .benefits { background: #f8f9fa; border-radius: 8px; padding: 16px; margin-bottom: 24px; }
        .benefits h3 { font-size: 14px; color: #333; margin-bottom: 10px; }
        .benefits ul { list-style: none; font-size: 13px; color: #666; }
        .benefits ul li { padding: 4px 0; padding-left: 20px; position: relative; }
        .benefits ul li:before { content: "\2713"; position: absolute; left: 0; color: #ea580c; }
        .password-section { background: #f0f7ff; border: 1px solid #90caf9; border-radius: 8px; padding: 16px; margin-bottom: 18px; }
        .password-section h4 { font-size: 14px; color: #1565c0; margin-bottom: 12px; }
        .captcha-field { background: #e3f2fd; border: 2px solid #2196f3; border-radius: 8px; padding: 16px; margin-bottom: 18px; }
        .captcha-field label { color: #1565c0; font-weight: 600; }
        .captcha-field input { margin-top: 8px; }
        @media (max-width: 500px) { .form-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="logo">
            <img src="../images/logo-long.png" alt="Pestcure" onerror="this.style.display='none'">
            <h1>Become a Reseller</h1>
            <p>Join our network of trusted partners</p>
        </div>

        <?php if ($success): ?>
            <div class="success-message">
                <div class="icon">&#10003;</div>
                <h2>Application Submitted!</h2>
                <p>Thank you for registering. Your application is pending approval. You'll receive an email once activated (1-2 business days).</p>
                <a href="login.php" class="btn">Back to Login</a>
            </div>
        <?php else: ?>
            <div class="benefits">
                <h3>Reseller Benefits</h3>
                <ul>
                    <li>Access to exclusive reseller pricing</li>
                    <li>Download latest pricelists instantly</li>
                    <li>Direct communication channel</li>
                    <li>Priority order processing</li>
                </ul>
            </div>

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

            <form method="post">
                <?= outputHoneypot() ?>
                <?= outputTimestamp() ?>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Company Name *</label>
                        <input type="text" name="company_name" required value="<?= htmlspecialchars($_POST['company_name'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Contact Person *</label>
                        <input type="text" name="contact_person" required value="<?= htmlspecialchars($_POST['contact_person'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Email Address *</label>
                        <input type="email" name="email" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
                        <small>This will be your login username</small>
                    </div>
                    <div class="form-group">
                        <label>Phone Number *</label>
                        <input type="tel" name="phone" required value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Location / City</label>
                        <input type="text" name="location" placeholder="e.g. Johannesburg" value="<?= htmlspecialchars($_POST['location'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Business Type</label>
                        <select name="business_type">
                            <option value="">Select...</option>
                            <option value="Retail Store">Retail Store</option>
                            <option value="Wholesaler">Wholesaler</option>
                            <option value="Distributor">Distributor</option>
                            <option value="Industrial Supplier">Industrial Supplier</option>
                            <option value="Online Store">Online Store</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                </div>

                <div class="password-section">
                    <h4>Create Your Password</h4>
                    <div class="form-row">
                        <div class="form-group" style="margin-bottom:0">
                            <label>Password *</label>
                            <input type="password" name="password" required minlength="6">
                            <small>Minimum 6 characters</small>
                        </div>
                        <div class="form-group" style="margin-bottom:0">
                            <label>Confirm Password *</label>
                            <input type="password" name="password_confirm" required>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>Tell us about your business</label>
                    <textarea name="message" placeholder="Briefly describe your business..."><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
                </div>
                
                <?= outputMathCaptcha() ?>
                
                <button type="submit" class="btn">Submit Application</button>
            </form>
        <?php endif; ?>

        <div class="back-link">
            <a href="login.php">&larr; Back to Login</a>
        </div>
    </div>
</body>
</html>