<?php include 'header.php'; ?>
<?php
$msg = '';

// Helper to JSON-encode arrays consistently
function to_json($value) {
    if (is_array($value)) {
        return json_encode(array_values($value));
    }
    if (is_string($value)) {
        return $value;
    }
    return json_encode([]);
}

// Fetch current settings
$settings = null;
$stmt = $conn->prepare("SELECT * FROM upwork_settings WHERE user_id = ? LIMIT 1");
$stmt->bind_param("s", $userId);
if ($stmt->execute()) {
    $res = $stmt->get_result();
    if ($res && $res->num_rows === 1) {
        $settings = $res->fetch_assoc();
    }
}
$stmt->close();

// Defaults
$default_location = ["Africa", "Antarctica", "Central America"];

// Current values
$current_location = $default_location;
if ($settings && !empty($settings['location'])) {
    $decoded = json_decode($settings['location'], true);
    if (is_array($decoded)) {
        $current_location = $decoded;
    }
}

// Options
$regions = ["Africa", "Americas", "Antarctica", "Asia", "Europe", "Oceania"];
$subregions = [
    "Australia and New Zealand", "Caribbean", "Central America", "Central Asia",
    "Eastern Africa", "Eastern Asia", "Eastern Europe", "Melanesia", "Micronesia",
    "Middle Africa", "Northern Africa", "Northern America", "Northern Europe",
    "Polynesia", "South America", "South-Eastern Asia", "Southern Africa",
    "Southern Asia", "Southern Europe", "Western Africa", "Western Asia", "Western Europe"
];
$countries = [
    "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bonaire, Sint Eustatius and Saba", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "British Virgin Islands", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia", "Curacao", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern and Antarctic Lands", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territories", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda", "Saint Barthelemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin (French part)", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Korea", "Spain", "Sri Lanka", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "United States Virgin Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"
];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $location = isset($_POST['location']) && is_array($_POST['location']) ? array_values($_POST['location']) : [];

    if ($settings) {
        $query = "UPDATE upwork_settings SET location = ?, updated_at = NOW() WHERE user_id = ?";
        $stmt = $conn->prepare($query);
        $location_json = to_json($location);
        $stmt->bind_param("ss", $location_json, $userId);
        if ($stmt->execute()) {
            $msg = '<div class="alert alert-success alert-top-border alert-dismissible fade show" role="alert">
                        <i class="ri-check-double-line me-3 align-middle fs-16 text-success"></i><strong>Success</strong> - Countries settings updated
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
            $current_location = $location;
        } else {
            $msg = '<div class="alert alert-danger alert-top-border alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-3 align-middle fs-16 text-danger"></i><strong>Error</strong> - Failed to update settings
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
        }
        $stmt->close();
    } else {
        $query = "INSERT INTO upwork_settings (user_id, location, created_at, updated_at) VALUES (?, ?, NOW(), NOW())";
        $stmt = $conn->prepare($query);
        $location_json = to_json($location);
        $stmt->bind_param("ss", $userId, $location_json);
        if ($stmt->execute()) {
     $msg = '<div class="alert alert-success alert-top-border alert-dismissible fade show" role="alert">
                        <i class="ri-check-double-line me-3 align-middle fs-16 text-success"></i><strong>Success</strong> - Countries settings saved
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>';
            $current_location = $location;
} else {
      $msg = '<div class="alert alert-danger alert-top-border alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-3 align-middle fs-16 text-danger"></i><strong>Error</strong> - Failed to save settings
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>';
}
        $stmt->close();
    }
}
?>

<div class="page-content">
    <div class="container-fluid">

        <div class="row">
            <div class="col-12">
                <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-transparent">
                    <h4 class="mb-sm-0">Countries Settings</h4>
                    <div class="page-title-right">
                        <ol class="breadcrumb m-0">
                            <li class="breadcrumb-item"><a href="javascript: void(0);">Dashboard</a></li>
                            <li class="breadcrumb-item active">Countries</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <center>
            <div class="col-lg-8">
                <?php echo $msg; ?>

                <div class="card card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-xl me-3">
                            <div class="avatar-title bg-transparent text-primary rounded" style="font-size: 60px">
                                <i class="ri-map-pin-line"></i>
                            </div>
                        </div>
                        <div>
                            <h2 class="mb-0">Countries</h2>
                            <p class="text-muted mb-0">Select countries and regions for job discovery.</p>
                        </div>
                    </div>

                    <form method="POST" class="p-2">
                        <div class="mb-3 text-start">
                            <label class="form-label">Location</label>

                            <button type="button" class="btn btn-outline-secondary w-100 d-flex justify-content-between align-items-center" onclick="document.getElementById('locationDropdown').classList.toggle('d-none');">
                                <span><?php echo count($current_location) > 0 ? count($current_location) . ' selected' : 'Select locations'; ?></span>
                                <span><i class="ri-arrow-down-s-line"></i></span>
                            </button>

                            <?php if (count($current_location) > 0) { ?>
                            <div class="mt-3">
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($current_location as $loc) { ?>
                                        <span class="badge bg-light text-primary border" style="border-color: #6f5fc5 !important;">
                                            <?php echo htmlspecialchars($loc); ?>
                                        </span>
                                    <?php } ?>
                                </div>
                            </div>
                            <?php } ?>

                            <div id="locationDropdown" class="mt-2 p-3 border rounded shadow d-none" style="max-height: 420px; overflow-y: auto;">
                                <p class="fw-bold text-success">Region</p>
                                <div class="row g-2">
                                    <?php foreach ($regions as $loc) { $checked = in_array($loc, $current_location); ?>
                                    <div class="col-12 col-md-6">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="region_<?php echo md5($loc); ?>" name="location[]" value="<?php echo htmlspecialchars($loc); ?>" <?php echo $checked ? 'checked' : '' ; ?>>
                                            <label class="form-check-label" for="region_<?php echo md5($loc); ?>"><?php echo htmlspecialchars($loc); ?></label>
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>

                                <hr>
                                <p class="fw-bold text-success">Subregion</p>
                                <div class="row g-2">
                                    <?php foreach ($subregions as $loc) { $checked = in_array($loc, $current_location); ?>
                                    <div class="col-12 col-md-6">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="subregion_<?php echo md5($loc); ?>" name="location[]" value="<?php echo htmlspecialchars($loc); ?>" <?php echo $checked ? 'checked' : '' ; ?>>
                                            <label class="form-check-label" for="subregion_<?php echo md5($loc); ?>"><?php echo htmlspecialchars($loc); ?></label>
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>

                                <hr>
                                <p class="fw-bold text-success">Countries</p>
                                <div class="row g-2">
                                    <?php foreach ($countries as $loc) { $checked = in_array($loc, $current_location); ?>
                                    <div class="col-12 col-md-6">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="country_<?php echo md5($loc); ?>" name="location[]" value="<?php echo htmlspecialchars($loc); ?>" <?php echo $checked ? 'checked' : '' ; ?>>
                                            <label class="form-check-label" for="country_<?php echo md5($loc); ?>"><?php echo htmlspecialchars($loc); ?></label>
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>
    </div>
                        </div>

                        <button type="submit" class="btn btn-success w-100">Save settings</button>
                    </form>
                </div>
            </div>
        </center>
    </div>

    <?php include 'footer.php'; ?>