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

// Helpers
function to_json($value) {
    if (is_array($value)) {
        return json_encode(array_values($value));
    }
    if (is_string($value)) {
        return $value;
    }
    return json_encode([]);
}

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

// Defaults for form state if nothing saved yet
$default_client_hires = ["1-9", "10-"];
$default_verified_payment = true;

// Derive current values for the form
$current_client_hires = $default_client_hires;
if ($settings && !empty($settings['client_hires'])) {
    $decoded = json_decode($settings['client_hires'], true);
    if (is_array($decoded)) {
        $current_client_hires = $decoded;
    }
}
$current_verified_payment = $default_verified_payment;
if ($settings !== null) {
    $current_verified_payment = isset($settings['verified_payment']) ? (intval($settings['verified_payment']) === 1) : $default_verified_payment;
}

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

    // Persist: update if exists, else insert
    if ($settings) {
        $query = "UPDATE upwork_settings SET client_hires = ?, verified_payment = ?, updated_at = NOW() WHERE user_id = ?";
        $stmt = $conn->prepare($query);
        $client_hires_json = to_json($client_hires);
        $stmt->bind_param("sis", $client_hires_json, $verified_payment, $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> - Client settings updated
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
            $current_client_hires = $client_hires;
            $current_verified_payment = ($verified_payment === 1);
        } 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, client_hires, verified_payment, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())";
        $stmt = $conn->prepare($query);
        $client_hires_json = to_json($client_hires);
        $stmt->bind_param("ssi", $userId, $client_hires_json, $verified_payment);
        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> - Client settings saved
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
            $current_client_hires = $client_hires;
            $current_verified_payment = ($verified_payment === 1);
        } 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">Client Stats</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">Client Stats</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

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

                <div class="card card-body text-center">
                    <div class="avatar-xl mx-auto mb-3 mt-4">
                        <div class="avatar-title bg-transparent text-success rounded" style="font-size: 100px">
                            <i class="ri-team-line"></i>
                        </div>
                    </div>
                    <h2>Client Settings</h2>
                    <p class="card-text text-muted">Configure client hiring preferences and payment verification.</p>

                    <form method="POST" class="p-4">
                        <div class="mb-4 text-start">
                            <label class="form-label">Client Hires</label>
                            <div class="row g-3">
                                <div class="col-12 col-md-6">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="hire_1_9" name="client_hires[]" value="1-9" <?php echo in_array("1-9", $current_client_hires) ? 'checked' : '' ; ?>>
                                        <label class="form-check-label" for="hire_1_9">1-9 Hires</label>
                                    </div>
                                </div>
                                <div class="col-12 col-md-6">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="hire_10_plus" name="client_hires[]" value="10-" <?php echo in_array("10-", $current_client_hires) ? 'checked' : '' ; ?>>
                                        <label class="form-check-label" for="hire_10_plus">10+ Hires</label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mb-4 text-start">
                            <label class="form-label">Verified Payment Only</label>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="verified_payment" name="verified_payment" <?php echo $current_verified_payment ? 'checked' : '' ; ?>>
                                <label class="form-check-label" for="verified_payment">Verified Payment Only</label>
                            </div>
                        </div>

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

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


