<?php
session_start();
include '../includes/config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo "<div class='alert alert-danger'>Please login first.</div>";
    echo "<script>showToast('Error', 'Please login first.', 'danger');</script>";
    exit;
}

$user_id = $_SESSION['user_id'];

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

    // Get and sanitize form data
    $id_number = mysqli_real_escape_string($conn, $_POST['id_number']);
    $date_of_birth = mysqli_real_escape_string($conn, $_POST['date_of_birth']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $city = mysqli_real_escape_string($conn, $_POST['city']);
    $province = mysqli_real_escape_string($conn, $_POST['province']);
    $postal_code = mysqli_real_escape_string($conn, $_POST['postal_code']);
    $employment_status = mysqli_real_escape_string($conn, $_POST['employment_status']);
    $monthly_income = mysqli_real_escape_string($conn, $_POST['monthly_income']);

    // Validate required fields
    if (empty($id_number) || empty($date_of_birth) || empty($address) || empty($city) || empty($province) || empty($postal_code) || empty($employment_status) || empty($monthly_income)) {
        echo "<div class='alert alert-danger'>All required fields must be filled.</div>";
        echo "<script>showToast('Error', 'All required fields must be filled.', 'danger');</script>";
        exit;
    }

    // Validate ID number (13 digits)
    if (strlen($id_number) !== 13 || !is_numeric($id_number)) {
        echo "<div class='alert alert-danger'>Please provide a valid 13-digit ID number.</div>";
        echo "<script>showToast('Error', 'Please provide a valid 13-digit ID number.', 'danger');</script>";
        exit;
    }

    // Validate age (must be 18+)
    $dob = new DateTime($date_of_birth);
    $today = new DateTime();
    $age = $today->diff($dob)->y;
    if ($age < 18) {
        echo "<div class='alert alert-danger'>You must be at least 18 years old to register.</div>";
        echo "<script>showToast('Error', 'You must be at least 18 years old to register.', 'danger');</script>";
        exit;
    }

    // Validate postal code (4 digits)
    if (strlen($postal_code) !== 4 || !is_numeric($postal_code)) {
        echo "<div class='alert alert-danger'>Please provide a valid 4-digit postal code.</div>";
        echo "<script>showToast('Error', 'Please provide a valid 4-digit postal code.', 'danger');</script>";
        exit;
    }

    // Validate monthly income (positive number)
    if ($monthly_income < 0 || !is_numeric($monthly_income)) {
        echo "<div class='alert alert-danger'>Please provide a valid monthly income.</div>";
        echo "<script>showToast('Error', 'Please provide a valid monthly income.', 'danger');</script>";
        exit;
    }

    // Check if ID number already exists (for other users)
    $check_id_sql = "SELECT id FROM users WHERE id_number = '$id_number' AND id != '$user_id'";
    $id_result = mysqli_query($conn, $check_id_sql);
    
    if (!$id_result) {
        echo "<div class='alert alert-danger'>Database error: " . mysqli_error($conn) . "</div>";
        echo "<script>showToast('Error', 'Database error occurred.', 'danger');</script>";
        exit;
    }
    
    if (mysqli_num_rows($id_result) > 0) {
        echo "<div class='alert alert-danger'>This ID number is already registered with another account.</div>";
        echo "<script>showToast('Error', 'This ID number is already registered with another account.', 'danger');</script>";
        exit;
    }

    // Update user profile in database
    $update_query = "UPDATE users SET 
        id_number = '$id_number',
        date_of_birth = '$date_of_birth',
        address = '$address',
        city = '$city',
        province = '$province',
        postal_code = '$postal_code',
        employment_status = '$employment_status',
        monthly_income = '$monthly_income',
        registration_complete = 1
    WHERE id = '$user_id'";

    $result = mysqli_query($conn, $update_query);

    if ($result) {
        // Update session
        $_SESSION['registration_complete'] = 1;
        $_SESSION['user_status'] = 'verified';

        // Get user info for email
        $user_sql = "SELECT first_name, email FROM users WHERE id = '$user_id'";
        $user_result = mysqli_query($conn, $user_sql);
        
        if (!$user_result) {
            echo "<div class='alert alert-danger'>Error fetching user data: " . mysqli_error($conn) . "</div>";
            echo "<script>showToast('Error', 'Error fetching user data.', 'danger');</script>";
            exit;
        }
        
        $user_data = mysqli_fetch_assoc($user_result);
        
        if ($user_data) {
            $first_name = $user_data['first_name'];
            $email = $user_data['email'];

            // Send confirmation email
            $mail_subject = "Profile Completed Successfully - $sitename";
            $mail_message = "
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    .email-container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
                    .header { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; padding: 30px; text-align: center; }
                    .content { padding: 30px; background: #f8f9fa; }
                    .success-box { background: white; padding: 20px; border-radius: 10px; margin: 20px 0; text-align: center; }
                    .button { background: #28a745; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; }
                    .footer { text-align: center; padding: 20px; color: #6c757d; font-size: 12px; }
                </style>
            </head>
            <body>
                <div class='email-container'>
                    <div class='header'>
                        <h1>Profile Completed! 🎉</h1>
                    </div>
                    <div class='content'>
                        <h2>Congratulations, $first_name!</h2>
                        <p>Your profile has been successfully completed and is now under verification.</p>
                        
                        <div class='success-box'>
                            <h3>What's Next?</h3>
                            <p>Your information is being reviewed by our team. You'll be able to:</p>
                            <ul style='text-align: left;'>
                                <li>Apply for loans</li>
                                <li>Check your credit score</li>
                                <li>Access exclusive financial products</li>
                            </ul>
                        </div>

                        <p>Verification typically takes 24-48 hours. You'll receive an email once your account is fully verified.</p>
                        
                        <a href='$myUrl/dashboard/dashboard.php' class='button'>Go to Dashboard</a>
                    </div>
                    <div class='footer'>
                        <p>Thank you for choosing $sitename for your financial needs.</p>
                    </div>
                </div>
            </body>
            </html>";

            // Include your mail sender
            if (file_exists("proccess/mail_sender.php")) {
                include("proccess/mail_sender.php");
            }
        }

        echo "<div class='alert alert-success'>
            <h4>Profile Completed Successfully! 🎉</h4>
            <p>Thank you for completing your profile, <strong>$first_name</strong>!</p>
            <p>Your information has been submitted for verification. You can now access your dashboard.</p>
            
            <div class='mt-3'>
                <p><strong>What happens next?</strong></p>
                <ul>
                    <li>Your documents will be verified within 24-48 hours</li>
                    <li>You'll receive email confirmation once verified</li>
                    <li>You can now apply for loans and access financial products</li>
                </ul>
            </div>
            
            <div class='mt-4'>
                <a href='dashboard.php' class='btn btn-success me-2'>
                    <i class='fas fa-tachometer-alt me-1'></i> Go to Dashboard
                </a>
                <a href='loan-application.php' class='btn btn-outline-primary'>
                    <i class='fas fa-hand-holding-usd me-1'></i> Apply for Loan
                </a>
            </div>
        </div>";

        echo "<script>
            showToast('Success', 'Profile completed successfully! Redirecting to dashboard...', 'success');
            setTimeout(function() {
                window.location.href = 'dashboard.php';
            }, 3000);
        </script>";

        // Log the profile completion
        error_log("User $user_id completed profile registration");

    } else {
        echo "<div class='alert alert-danger'>Error updating profile: " . mysqli_error($conn) . "</div>";
        echo "<script>showToast('Error', 'Error updating profile. Please try again.', 'danger');</script>";
    }

} else {
    echo "<div class='alert alert-danger'>Invalid request method.</div>";
    echo "<script>showToast('Error', 'Invalid request method.', 'danger');</script>";
}

mysqli_close($conn);
?>