<?php
// register.php
session_start();
require_once 'config/database.php';

$database = new Database();
$db = $database->getConnection();

if (!function_exists('h')) {
    function h($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function findLocationByZip(PDO $db, string $zipCode): ?array {
    $zipCode = trim($zipCode);

    if (!preg_match('/^\d{5}$/', $zipCode)) {
        return null;
    }

    $stmt = $db->prepare("\n        SELECT\n            sa.zip_code,\n            sa.city,\n            sa.state,\n            sa.region,\n            c.id AS city_id\n        FROM service_areas sa\n        LEFT JOIN cities c\n            ON LOWER(TRIM(c.city_name)) = LOWER(TRIM(sa.city))\n            AND (LOWER(TRIM(c.state)) = LOWER(TRIM(sa.state)) OR c.state IS NULL OR c.state = '')\n            AND c.is_active = 1\n        WHERE sa.zip_code = :zip_code\n          AND sa.is_active = 1\n        ORDER BY sa.city ASC\n        LIMIT 1\n    ");
    $stmt->execute([':zip_code' => $zipCode]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ?: null;
}

// AJAX ZIP lookup using service_areas: register.php?action=lookup_zip&zip_code=12345
if (isset($_GET['action']) && $_GET['action'] === 'lookup_zip') {
    header('Content-Type: application/json');

    $zipCode = trim($_GET['zip_code'] ?? '');
    $location = findLocationByZip($db, $zipCode);

    if ($location) {
        echo json_encode([
            'success' => true,
            'zip_code' => $location['zip_code'],
            'city' => $location['city'],
            'city_id' => $location['city_id'],
            'state' => $location['state'],
            'region' => $location['region']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'ZIP code not found in the active service area list.'
        ]);
    }
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = preg_replace('/[^0-9]/', '', $_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $zip_code = trim($_POST['zip_code'] ?? '');
    $city_id = !empty($_POST['city_id']) ? intval($_POST['city_id']) : null;
    $city_name = trim($_POST['city_name'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $region = trim($_POST['region'] ?? '');
    $terms = isset($_POST['terms']);

    // If ZIP is provided, use the official service_areas data instead of trusting hidden fields.
    if ($zip_code !== '') {
        $zipLocation = findLocationByZip($db, $zip_code);
        if ($zipLocation) {
            $city_id = !empty($zipLocation['city_id']) ? intval($zipLocation['city_id']) : null;
            $city_name = $zipLocation['city'];
            $state = $zipLocation['state'];
            $region = $zipLocation['region'];
        }
    } else {
        $zipLocation = null;
    }

    if (empty($first_name) || empty($last_name) || empty($email) || empty($phone) || empty($password)) {
        $error = 'All required fields must be filled.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters long.';
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match.';
    } elseif (!preg_match('/^[0-9]{10}$/', $phone)) {
        $error = 'Please enter a valid 10-digit phone number.';
    } elseif ($zip_code !== '' && !preg_match('/^\d{5}$/', $zip_code)) {
        $error = 'Please enter a valid 5-digit ZIP code.';
    } elseif ($zip_code !== '' && empty($zipLocation)) {
        $error = 'This ZIP code is not currently in our active service area list.';
    } elseif (!$terms) {
        $error = 'You must agree to the Terms and Conditions.';
    } else {
        $checkStmt = $db->prepare('SELECT id FROM customers WHERE email = :email LIMIT 1');
        $checkStmt->execute([':email' => $email]);

        if ($checkStmt->fetch()) {
            $error = 'Email address already registered. Please login or use a different email.';
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $verification_token = bin2hex(random_bytes(32));

            $query = "\n                INSERT INTO customers (\n                    first_name, last_name, email, phone_number, password,\n                    address, region, city_id, state, zip_code, verification_token\n                ) VALUES (\n                    :first_name, :last_name, :email, :phone, :password,\n                    :address, :region, :city_id, :state, :zip_code, :verification_token\n                )\n            ";

            $stmt = $db->prepare($query);

            try {
                $stmt->execute([
                    ':first_name' => $first_name,
                    ':last_name' => $last_name,
                    ':email' => $email,
                    ':phone' => $phone,
                    ':password' => $hashed_password,
                    ':address' => $address,
                    ':region' => $region ?: null,
                    ':city_id' => $city_id ?: null,
                    ':state' => $state ?: null,
                    ':zip_code' => $zip_code ?: null,
                    ':verification_token' => $verification_token
                ]);

                $success = 'Registration successful! Redirecting to your dashboard...';

                $_SESSION['customer_id'] = $db->lastInsertId();
                $_SESSION['customer_name'] = $first_name . ' ' . $last_name;
                $_SESSION['customer_email'] = $email;

                header('refresh:3;url=customer/dashboard.php');
            } catch (PDOException $e) {
                $error = 'Registration failed. Please try again.';
                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, maximum-scale=1.0, user-scalable=no">
    <title>Register - Home Service App</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
        .register-container { max-width: 700px; width: 100%; margin: 0 auto; }
        .register-card { background: white; border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); overflow: hidden; }
        .register-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; }
        .register-header h2 { font-size: 28px; font-weight: 700; margin-bottom: 10px; }
        .register-header p { font-size: 14px; opacity: 0.9; margin-bottom: 0; }
        .register-body { padding: 30px; }
        .form-label { font-weight: 500; color: #495057; font-size: 14px; }
        .form-control, .form-select { border-radius: 10px; border: 2px solid #e0e0e0; padding: 12px 15px; font-size: 15px; transition: all 0.3s; }
        .form-control:focus, .form-select:focus { border-color: #667eea; box-shadow: 0 0 0 0.2rem rgba(102,126,234,0.25); }
        .input-group-text { background: white; border: 2px solid #e0e0e0; border-radius: 10px 0 0 10px; }
        .btn-register { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 10px; padding: 14px; font-weight: 600; font-size: 16px; width: 100%; transition: transform 0.3s; }
        .btn-register:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.4); color: white; }
        .login-link { text-align: center; margin-top: 20px; }
        .login-link a { color: #667eea; text-decoration: none; font-weight: 600; }
        .login-link a:hover { text-decoration: underline; }
        .terms-check { margin: 20px 0; }
        .password-strength { height: 5px; border-radius: 5px; margin-top: 5px; transition: all 0.3s; }
        .weak-password { background: #dc3545; width: 33%; }
        .medium-password { background: #ffc107; width: 66%; }
        .strong-password { background: #28a745; width: 100%; }
        .alert { border-radius: 10px; border: none; }
        .location-status { font-size: 13px; margin-top: 6px; }
        .readonly-location { background-color: #f8f9fa; }
        @media (max-width: 576px) { .register-header { padding: 20px; } .register-header h2 { font-size: 24px; } .register-body { padding: 20px; } }
    </style>
    <link rel="stylesheet" href="assets/theme.css">
    <link rel="stylesheet" href="assets/portal-dark.css">
    <link rel="stylesheet" href="assets/ushs-global-theme.css">
</head>
<body>
    <div class="register-container">
        <div class="register-card">
            <div class="register-header">
                <i class="fas fa-tools fa-4x mb-3"></i>
                <h2>Create Account</h2>
                <p>Join Home Service to get professional appliance repair</p>
            </div>

            <div class="register-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle me-2"></i><?= h($error); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i><?= h($success); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form method="POST" action="" id="registerForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">First Name <span class="text-danger">*</span></label>
                            <input type="text" name="first_name" class="form-control" value="<?= h($_POST['first_name'] ?? ''); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Last Name <span class="text-danger">*</span></label>
                            <input type="text" name="last_name" class="form-control" value="<?= h($_POST['last_name'] ?? ''); ?>" required>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Email Address <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                            <input type="email" name="email" class="form-control" value="<?= h($_POST['email'] ?? ''); ?>" required>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Phone Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-phone"></i></span>
                            <input type="tel" name="phone" class="form-control" value="<?= h($_POST['phone'] ?? ''); ?>" placeholder="10-digit number" pattern="[0-9]{10}" required>
                        </div>
                        <small class="text-muted">Enter 10-digit mobile number</small>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                <input type="password" name="password" id="password" class="form-control" minlength="8" required>
                            </div>
                            <div class="password-strength" id="passwordStrength"></div>
                            <small class="text-muted">Minimum 8 characters</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
                            </div>
                            <div id="passwordMatch" class="small mt-1"></div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Service Address</label>
                        <textarea name="address" class="form-control" rows="2"><?= h($_POST['address'] ?? ''); ?></textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Region</label>
                            <input type="text" name="region" id="region" class="form-control readonly-location" value="<?= h($_POST['region'] ?? ''); ?>" readonly>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">City</label>
                            <input type="text" name="city_name" id="city_name" class="form-control readonly-location" value="<?= h($_POST['city_name'] ?? ''); ?>" readonly>
                            <input type="hidden" name="city_id" id="city_id" value="<?= h($_POST['city_id'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">State</label>
                            <input type="text" name="state" id="state" class="form-control readonly-location" value="<?= h($_POST['state'] ?? ''); ?>" readonly>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">ZIP Code</label>
                            <input type="text" name="zip_code" id="zip_code" class="form-control" maxlength="5" pattern="\d{5}" value="<?= h($_POST['zip_code'] ?? ''); ?>" placeholder="Enter 5-digit ZIP">
                            <div id="zipStatus" class="location-status text-muted"></div>
                        </div>
                    </div>

                    <div class="terms-check">
                        <div class="form-check">
                            <input type="checkbox" name="terms" id="terms" class="form-check-input" required <?= isset($_POST['terms']) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="terms">
                                I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms and Conditions</a> and
                                <a href="#" data-bs-toggle="modal" data-bs-target="#privacyModal">Privacy Policy</a> <span class="text-danger">*</span>
                            </label>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-register" id="submitBtn">
                        <i class="fas fa-user-plus me-2"></i>Create Account
                    </button>

                    <div class="login-link">
                        Already have an account? <a href="login.php">Login here</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="termsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Terms and Conditions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <h6>1. Service Agreement</h6>
                    <p>By using our service, you agree to provide accurate information and allow our technicians to access your premises for repairs.</p>
                    <h6>2. Payment Terms</h6>
                    <p>Payment is due upon completion of service. We accept cash, credit cards, and online payments.</p>
                    <h6>3. Cancellation Policy</h6>
                    <p>Cancellations must be made at least 2 hours before scheduled appointment to avoid fees.</p>
                    <h6>4. Warranty</h6>
                    <p>All repairs come with a 30-day warranty on parts and labor.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="privacyModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Privacy Policy</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <h6>Information Collection</h6>
                    <p>We collect personal information to provide better service and communicate with you about your requests.</p>
                    <h6>Data Security</h6>
                    <p>Your information is encrypted and stored securely. We never share your data with third parties.</p>
                    <h6>Communication</h6>
                    <p>We may send you service updates and promotional offers. You can opt out anytime.</p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        $(document).ready(function() {
            function setLocation(data) {
                $('#city_name').val(data.city || '');
                $('#city_id').val(data.city_id || '');
                $('#state').val(data.state || '');
                $('#region').val(data.region || '');
            }

            function clearLocation() {
                $('#city_name').val('');
                $('#city_id').val('');
                $('#state').val('');
                $('#region').val('');
            }

            function lookupZip() {
                let zip = $('#zip_code').val();
                let status = $('#zipStatus');

                if (zip.length < 5) {
                    clearLocation();
                    status.removeClass('text-success text-danger').addClass('text-muted').text('');
                    return;
                }

                status.removeClass('text-success text-danger').addClass('text-muted').text('Checking ZIP code...');

                $.ajax({
                    url: 'register.php',
                    method: 'GET',
                    dataType: 'json',
                    data: { action: 'lookup_zip', zip_code: zip },
                    success: function(response) {
                        if (response.success) {
                            setLocation(response);
                            status.removeClass('text-muted text-danger').addClass('text-success')
                                .text('Auto-filled from service area: ' + response.region + ' > ' + response.city + ' > ' + response.state);
                        } else {
                            clearLocation();
                            status.removeClass('text-muted text-success').addClass('text-danger').text(response.message);
                        }
                    },
                    error: function() {
                        clearLocation();
                        status.removeClass('text-muted text-success').addClass('text-danger').text('Could not check ZIP code. Please try again.');
                    }
                });
            }

            $('#zip_code').on('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 5);
                lookupZip();
            });

            if ($('#zip_code').val().length === 5) {
                lookupZip();
            }

            $('#password').on('keyup', function() {
                let password = $(this).val();
                let strength = checkPasswordStrength(password);
                let strengthBar = $('#passwordStrength');

                strengthBar.removeClass('weak-password medium-password strong-password');
                if (strength === 'weak') strengthBar.addClass('weak-password');
                else if (strength === 'medium') strengthBar.addClass('medium-password');
                else if (strength === 'strong') strengthBar.addClass('strong-password');

                checkPasswordMatch();
            });

            $('#confirm_password').on('keyup', checkPasswordMatch);

            function checkPasswordStrength(password) {
                if (password.length < 8) return 'weak';
                let strength = 0;
                if (/[A-Z]/.test(password)) strength++;
                if (/[a-z]/.test(password)) strength++;
                if (/\d/.test(password)) strength++;
                if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) strength++;
                if (strength < 2) return 'weak';
                if (strength < 3) return 'medium';
                return 'strong';
            }

            function checkPasswordMatch() {
                let password = $('#password').val();
                let confirm = $('#confirm_password').val();
                let matchDiv = $('#passwordMatch');

                if (confirm.length > 0) {
                    if (password === confirm) {
                        matchDiv.html('<span class="text-success"><i class="fas fa-check"></i> Passwords match</span>');
                    } else {
                        matchDiv.html('<span class="text-danger"><i class="fas fa-times"></i> Passwords do not match</span>');
                    }
                } else {
                    matchDiv.html('');
                }
            }

            $('#registerForm').on('submit', function(e) {
                if ($('#password').val() !== $('#confirm_password').val()) {
                    e.preventDefault();
                    alert('Passwords do not match!');
                    return;
                }

                let zip = $('#zip_code').val();
                if (zip.length > 0 && zip.length !== 5) {
                    e.preventDefault();
                    alert('Please enter a valid 5-digit ZIP code.');
                }
            });

            $('input[name="phone"]').on('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 10);
            });
        });
    </script>
</body>
</html>
