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

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

// Load existing 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 per spec
$default_budget = ["0-99", "100-499", "1000-4999", "500-999", "5000-"];
$default_proposals = ["0-4", "5-9", "10-14", "20-49", "15-19"];

// Current values
$current_budget = $default_budget;
if ($settings && !empty($settings['budget'])) {
    $decoded = json_decode($settings['budget'], true);
    if (is_array($decoded)) { $current_budget = $decoded; }
}
$current_proposals = $default_proposals;
if ($settings && !empty($settings['proposals'])) {
    $decoded = json_decode($settings['proposals'], true);
    if (is_array($decoded)) { $current_proposals = $decoded; }
}

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

    if ($settings) {
        $query = "UPDATE upwork_settings SET budget = ?, proposals = ?, updated_at = NOW() WHERE user_id = ?";
        $stmt = $conn->prepare($query);
        $budget_json = to_json($budget);
        $proposals_json = to_json($proposals);
        $stmt->bind_param("sss", $budget_json, $proposals_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> - Budget settings updated
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
            $current_budget = $budget;
            $current_proposals = $proposals;
        } 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, budget, proposals, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())";
        $stmt = $conn->prepare($query);
        $budget_json = to_json($budget);
        $proposals_json = to_json($proposals);
        $stmt->bind_param("sss", $userId, $budget_json, $proposals_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> - Budget settings saved
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>';
            $current_budget = $budget;
            $current_proposals = $proposals;
        } 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">Budget 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">Budget</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-slideshow-2-line"></i>
                            </div>
                        </div>
                        <div>
                            <h2 class="mb-0">Project Budget</h2>
                            <p class="text-muted mb-0">Configure budget ranges and proposal limits for job filtering.</p>
                        </div>
                    </div>

                    <form method="POST" class="p-2">
                        <div class="mb-4 text-start">
                            <label class="form-label">Budget</label>
                            <div class="row g-2">
                                <?php foreach (["0-99", "100-499", "500-999", "1000-4999", "5000-"] as $budget) { $checked = in_array($budget, $current_budget); ?>
                                <div class="col-12 col-md-6">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="budget_<?php echo md5($budget); ?>" name="budget[]" value="<?php echo $budget; ?>" <?php echo $checked ? 'checked' : '' ; ?>>
                                        <label class="form-check-label" for="budget_<?php echo md5($budget); ?>">
                                            <?php
                                                $map = [
                                                    '0-99' => '$0 - $99',
                                                    '100-499' => '$100 - $499',
                                                    '500-999' => '$500 - $999',
                                                    '1000-4999' => '$1,000 - $4,999',
                                                    '5000-' => '$5,000+',
                                                ];
                                                echo $map[$budget];
                                            ?>
                                        </label>
                                    </div>
                                </div>
                                <?php } ?>
                            </div>
                        </div>

                        <div class="mb-2 text-start">
                            <label class="form-label">Proposals</label>
                            <div class="row g-2">
                                <?php foreach (["0-4", "5-9", "10-14", "15-19", "20-49"] as $proposal) { $checked = in_array($proposal, $current_proposals); ?>
                                <div class="col-12 col-md-6">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="proposal_<?php echo md5($proposal); ?>" name="proposals[]" value="<?php echo $proposal; ?>" <?php echo $checked ? 'checked' : '' ; ?>>
                                        <label class="form-check-label" for="proposal_<?php echo md5($proposal); ?>">
                                            <?php
                                                $map = [
                                                    '0-4' => '0 - 4 Proposals',
                                                    '5-9' => '5 - 9 Proposals',
                                                    '10-14' => '10 - 14 Proposals',
                                                    '15-19' => '15 - 19 Proposals',
                                                    '20-49' => '20 - 49 Proposals',
                                                ];
                                                echo $map[$proposal];
                                            ?>
                                        </label>
                                    </div>
                                </div>
                                <?php } ?>
                            </div>
                        </div>

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

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

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

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mf = $_POST['min_fixed'];
$mh = $_POST['min_hourly'];

$query = "UPDATE budgets SET min_fixed = '$mf', min_hourly = '$mh' WHERE user_id = '$userId'";
if ($conn->query($query) === TRUE) {
     $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> - Project Budget settings updated
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>';
} 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> - Settings updation error
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>';
}
    
}

$sql = "SELECT * FROM budgets WHERE user_id='$userId'";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
    $brow = $result->fetch_assoc();
}
?>
<div class="page-content">
    <div class="container-fluid">

        <!-- start page title -->
        <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">Project Budget</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">Project Budget</li>
                        </ol>
                    </div>

                </div>
            </div>
        </div>
        <!-- end page title -->

        <center>

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

                    <h2>Project Budget</h2>



                    <form method="POST" class="p-4">

                        <div class="row row-cols-lg-auto align-items-center g-3 justify-content-center">


                            <div class="mb-2">
                                <label class="float-start" for="min_fixed">Minimum fixed budget</label>
                                <input type="number" class="form-control" id="min_fixed" name="min_fixed" value="<?php echo $brow['min_fixed']; ?>" min="5">
                            </div>


                            <div class="mb-2">
                                <label class="float-start" for="min_hourly">Minimum hourly budget</label>
                                <input type="number" class="form-control" id="min_hourly" name="min_hourly" value="<?php echo $brow['min_hourly']; ?>" min="5">
                            </div>


                        </div>
                        <!--end row-->
                        <button type="submit" class="btn btn-success mt-4 w-100">Submit</button>
                    </form>
                </div>
            </div>





        </center>
        <!-- container-fluid -->
    </div>

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