<?php

include "../includes/admin_auth.php";
include "../config/database.php";


if (!isset($_GET['id'])) {

    header("Location: plans.php");
    exit();

}


$id = (int)$_GET['id'];


$stmt = $pdo->prepare("SELECT * FROM plans WHERE id=?");
$stmt->execute([$id]);

$plan = $stmt->fetch(PDO::FETCH_ASSOC);


if (!$plan) {

    die("Plan not found.");

}

?>


<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>

<title>Edit Scheme</title>


<link
rel="stylesheet"
href="../assets/css/admin.css"
>

<link
rel="stylesheet"
href="../assets/css/responsive.css"
>

<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
>


<style>

.current-plan-image {

    margin-top: 10px;

}

.current-plan-image img {

    width: 180px;

    height: 120px;

    object-fit: cover;

    border-radius: 10px;

    border: 1px solid #ddd;

}

.image-preview {

    display: none;

    margin-top: 12px;

}

.image-preview img {

    width: 180px;

    height: 120px;

    object-fit: cover;

    border-radius: 10px;

    border: 1px solid #ddd;

}

.form-help {

    display: block;

    margin-top: 6px;

    color: #777;

    font-size: 13px;

}

</style>

</head>


<body>


<?php include "../includes/admin_sidebar.php"; ?>

<div class="sidebar-overlay"></div>

<?php include "../includes/admin_topbar.php"; ?>


<div class="main-content">


<div class="page-header">

<div>

<h2>

<i class="fas fa-pen"></i>

Edit Scheme

</h2>

<p>

Update the information for this contribution scheme.

</p>

</div>

</div>


<div class="table-card">


<form
action="update_plan.php"
method="POST"
enctype="multipart/form-data"
class="plan-form"
>


<input
type="hidden"
name="id"
value="<?= (int)$plan['id']; ?>"
>


<div class="form-grid">


<!-- SCHEME NAME -->

<div class="form-group">

<label>Scheme Name</label>

<input
type="text"
name="plan_name"
class="form-control"
value="<?= htmlspecialchars($plan['plan_name']); ?>"
required
>

</div>


<!-- SCHEME TYPE -->

<div class="form-group">

<label>Scheme Type</label>

<select
name="plan_type"
class="form-control"
required
>

<option value="Savings"
<?= $plan['plan_type']=="Savings" ? "selected" : ""; ?>
>
Savings
</option>

<option value="Food"
<?= $plan['plan_type']=="Food" ? "selected" : ""; ?>
>
Food
</option>

<option value="Contribution"
<?= $plan['plan_type']=="Contribution" ? "selected" : ""; ?>
>
Contribution
</option>

</select>

</div>


<!-- AMOUNT -->

<div class="form-group">

<label>Contribution Amount Per Hand (₦)</label>

<input
type="number"
name="amount"
class="form-control"
value="<?= htmlspecialchars($plan['amount']); ?>"
min="1"
step="0.01"
required
>

</div>


<!-- FREQUENCY -->

<div class="form-group">

<label>Contribution Frequency</label>

<select
name="frequency"
class="form-control"
required
>

<option value="Daily"
<?= $plan['frequency']=="Daily" ? "selected" : ""; ?>
>
Daily
</option>

<option value="Weekly"
<?= $plan['frequency']=="Weekly" ? "selected" : ""; ?>
>
Weekly
</option>

<option value="Monthly"
<?= $plan['frequency']=="Monthly" ? "selected" : ""; ?>
>
Monthly
</option>

<option value="Yearly"
<?= $plan['frequency']=="Yearly" ? "selected" : ""; ?>
>
Yearly
</option>

</select>

</div>


<!-- DURATION -->

<div class="form-group">

<label>Duration (Months)</label>

<input
type="number"
name="duration"
class="form-control"
value="<?= htmlspecialchars($plan['duration']); ?>"
min="1"
required
>

</div>


<!-- START MONTH -->

<div class="form-group">

<label>Start Month</label>

<select
name="start_month"
id="start_month"
class="form-control"
required
>

<option value="">Select Start Month</option>

<?php

$months = [

1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December"

];


foreach ($months as $number => $name) {

    echo '<option value="'.$number.'" ' .
        ($plan['start_month'] == $number ? 'selected' : '') .
        '>'.$name.'</option>';

}

?>

</select>

</div>


<!-- START YEAR -->

<div class="form-group">

<label>Start Year</label>

<select
name="start_year"
id="start_year"
class="form-control"
required
>

<option value="">Select Start Year</option>

<?php

$startYear = 2025;

$currentYear = date("Y");

$selectedYear = (int)$plan['start_year'];

for (
    $year = $startYear;
    $year <= $currentYear + 10;
    $year++
) {

    echo '<option value="'.$year.'" ' .
        ($selectedYear == $year ? 'selected' : '') .
        '>'.$year.'</option>';

}

?>

</select>

</div>


<!-- PERIOD -->

<div
class="form-group"
style="grid-column:1 / -1;"
>

<label>Scheme Period</label>

<div
id="periodPreview"
style="
padding:12px 15px;
background:#f0f7ff;
border-left:4px solid #0d6efd;
border-radius:6px;
font-weight:600;
"
>

Loading scheme period...

</div>

</div>


<!-- DESCRIPTION -->

<div
class="form-group"
style="grid-column:1 / -1;"
>

<label>Short Description</label>

<textarea
name="description"
class="form-control"
rows="5"
required
><?= htmlspecialchars($plan['description']); ?></textarea>

</div>


<!-- PACKAGE ITEMS -->

<div
class="form-group"
style="grid-column:1 / -1;"
>

<label>Items / Package Contents</label>

<textarea
name="package_items"
class="form-control"
rows="7"
required
><?= htmlspecialchars($plan['package_items'] ?? ''); ?></textarea>

<small class="form-help">

Enter one item per line.

</small>

</div>


<!-- CURRENT IMAGE -->

<div
class="form-group"
style="grid-column:1 / -1;"
>

<label>Current Scheme Image</label>


<?php if (!empty($plan['plan_image'])): ?>

<div class="current-plan-image">

<img
src="../assets/uploads/plans/<?= htmlspecialchars($plan['plan_image']); ?>"
alt="Current Scheme Image"
>

</div>

<?php else: ?>

<p class="form-help">

No scheme image has been uploaded.

</p>

<?php endif; ?>

</div>


<!-- NEW IMAGE -->

<div
class="form-group"
style="grid-column:1 / -1;"
>

<label>Change Scheme Image</label>

<input
type="file"
name="plan_image"
id="plan_image"
class="form-control"
accept="image/jpeg,image/png,image/webp"
>

<small class="form-help">

Leave empty to keep the current image.

Maximum size: 5MB.

Accepted formats: JPG, PNG and WEBP.

</small>


<div
class="image-preview"
id="imagePreview"
>

<img
id="previewImage"
src=""
alt="New Scheme Image"
>

</div>

</div>


<!-- STATUS -->

<div class="form-group">

<label>Status</label>

<select
name="status"
class="form-control"
required
>

<option value="active"
<?= $plan['status']=="active" ? "selected" : ""; ?>
>
Active
</option>

<option value="inactive"
<?= $plan['status']=="inactive" ? "selected" : ""; ?>
>
Inactive
</option>

</select>

</div>


</div>


<div class="form-actions">


<a
href="plans.php"
class="back-btn"
>

<i class="fas fa-arrow-left"></i>

Back

</a>


<button
type="submit"
class="fund-btn"
>

<i class="fas fa-save"></i>

Update Scheme

</button>


</div>


</form>


</div>


</div>


<script src="../assets/js/admin.js"></script>


<script>

/*
|--------------------------------------------------------------------------
| Scheme Period
|--------------------------------------------------------------------------
*/

const startMonth =
document.getElementById("start_month");

const startYear =
document.getElementById("start_year");

const duration =
document.querySelector('input[name="duration"]');

const periodPreview =
document.getElementById("periodPreview");


function updatePeriod() {

    const month =
        parseInt(startMonth.value);

    const year =
        parseInt(startYear.value);

    const months =
        parseInt(duration.value);


    if (!month || !year || !months) {

        periodPreview.innerHTML =
        "Select the start month, year and duration.";

        return;

    }


    const startDate =
        new Date(
            year,
            month - 1,
            1
        );


    const endDate =
        new Date(
            year,
            (month - 1) + months - 1,
            1
        );


    const monthNames = [

        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"

    ];


    periodPreview.innerHTML =

        "📅 " +

        monthNames[startDate.getMonth()] +

        " " +

        startDate.getFullYear() +

        " – " +

        monthNames[endDate.getMonth()] +

        " " +

        endDate.getFullYear();

}


startMonth.addEventListener(
    "change",
    updatePeriod
);

startYear.addEventListener(
    "change",
    updatePeriod
);

duration.addEventListener(
    "input",
    updatePeriod
);


updatePeriod();


/*
|--------------------------------------------------------------------------
| New Image Preview
|--------------------------------------------------------------------------
*/

const imageInput =
document.getElementById("plan_image");

const imagePreview =
document.getElementById("imagePreview");

const previewImage =
document.getElementById("previewImage");


imageInput.addEventListener(
    "change",
    function () {

        const file = this.files[0];


        if (!file) {

            imagePreview.style.display =
                "none";

            return;

        }


        if (file.size > 5 * 1024 * 1024) {

            alert(
                "Image is too large. Maximum size is 5MB."
            );

            this.value = "";

            imagePreview.style.display =
                "none";

            return;

        }


        const reader =
            new FileReader();


        reader.onload =
        function (e) {

            previewImage.src =
                e.target.result;

            imagePreview.style.display =
                "block";

        };


        reader.readAsDataURL(file);

    }
);

</script>


</body>

</html>