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

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

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

// Get cities for dropdown
$cities = $validator->getActiveCities();

if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $address = trim($_POST['address']);
    $city_id = !empty($_POST['city_id']) ? intval($_POST['city_id']) : null;
    $zip_code = trim($_POST['zip_code']);
    $terms = isset($_POST['terms']);

    // Validation
    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(!$terms) {

        $error = "You must agree to the Terms and Conditions.";

    } else {

        // Check if email already exists
        $check_query = "SELECT id FROM customers WHERE email = :email";
        $check_stmt = $db->prepare($check_query);
        $check_stmt->execute([':email' => $email]);

        if($check_stmt->fetch()) {

            $error = "Email address already registered. Please login or use a different email.";

        } else {

            // Hash password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            // Generate verification token
            $verification_token = bin2hex(random_bytes(32));

            // Insert customer
            $query = "INSERT INTO customers (
                        first_name,
                        last_name,
                        email,
                        phone_number,
                        password,
                        address,
                        city_id,
                        zip_code,
                        verification_token
                    )
                    VALUES (
                        :first_name,
                        :last_name,
                        :email,
                        :phone,
                        :password,
                        :address,
                        :city_id,
                        :zip_code,
                        :verification_token
                    )";

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

            try {

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

                // SUCCESS MESSAGE
                $success = "Registration successful! Redirecting to login page...";

                // Redirect to unified login page
                header("refresh:2;url=login.php");
                exit();

            } 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: 600px;
            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;
        }
        
        @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>
                        <?php echo $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>
                        <?php echo $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="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_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="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_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="<?php echo isset($_POST['email']) ? htmlspecialchars($_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="<?php echo isset($_POST['phone']) ? htmlspecialchars($_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"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">City</label>
                            <select name="city_id" class="form-select">
                                <option value="">Select City</option>
                                <?php foreach($cities as $city): ?>
                                <option value="<?php echo $city['id']; ?>" 
                                        <?php echo (isset($_POST['city_id']) && $_POST['city_id'] == $city['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($city['city_name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">ZIP Code</label>
                            <input type="text" name="zip_code" class="form-control" maxlength="5" pattern="\d{5}" 
                                   value="<?php echo isset($_POST['zip_code']) ? htmlspecialchars($_POST['zip_code']) : ''; ?>">
                        </div>
                    </div>
                    
                    <div class="terms-check">
                        <div class="form-check">
                            <input type="checkbox" name="terms" id="terms" class="form-check-input" required>
                            <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>

    <!-- Terms Modal -->
    <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>

    <!-- Privacy Modal -->
    <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() {
            // Password strength checker
            $('#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 hasUpperCase = /[A-Z]/.test(password);
                let hasLowerCase = /[a-z]/.test(password);
                let hasNumbers = /\d/.test(password);
                let hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
                
                let strength = 0;
                if(hasUpperCase) strength++;
                if(hasLowerCase) strength++;
                if(hasNumbers) strength++;
                if(hasSpecial) 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('');
                }
            }
            
            // Form validation
            $('#registerForm').on('submit', function(e) {
                let password = $('#password').val();
                let confirm = $('#confirm_password').val();
                
                if(password !== confirm) {
                    e.preventDefault();
                    alert('Passwords do not match!');
                }
            });
            
            // Phone number formatting
            $('input[name="phone"]').on('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 10);
            });
            
            // ZIP code formatting
            $('input[name="zip_code"]').on('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '').substring(0, 5);
            });
        });
    </script>
</body>
</html>