<?php

session_start();

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


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

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

}


/*
|--------------------------------------------------------------------------
| Get ID
|--------------------------------------------------------------------------
*/

$id = (int)($_POST['id'] ?? 0);


if ($id <= 0) {

    $_SESSION['error'] = "Invalid scheme.";

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

}


/*
|--------------------------------------------------------------------------
| Get Existing Scheme
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT *
    FROM plans
    WHERE id=?
    LIMIT 1
");

$stmt->execute([$id]);

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


if (!$plan) {

    $_SESSION['error'] = "Scheme not found.";

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

}


/*
|--------------------------------------------------------------------------
| Get Form Data
|--------------------------------------------------------------------------
*/

$plan_name =
    trim($_POST['plan_name'] ?? '');

$plan_type =
    trim($_POST['plan_type'] ?? '');

$amount =
    (float)($_POST['amount'] ?? 0);

$frequency =
    trim($_POST['frequency'] ?? '');

$duration =
    !empty($_POST['duration'])
        ? (int)$_POST['duration']
        : null;

$start_month =
    !empty($_POST['start_month'])
        ? (int)$_POST['start_month']
        : null;

$start_year =
    !empty($_POST['start_year'])
        ? (int)$_POST['start_year']
        : null;

$description =
    trim($_POST['description'] ?? '');

$package_items =
    trim($_POST['package_items'] ?? '');

$status =
    trim($_POST['status'] ?? 'active');


/*
|--------------------------------------------------------------------------
| Validate
|--------------------------------------------------------------------------
*/

if (
    empty($plan_name) ||
    empty($plan_type) ||
    $amount <= 0 ||
    empty($frequency) ||
    empty($duration) ||
    empty($start_month) ||
    empty($start_year) ||
    empty($description) ||
    empty($package_items)
) {

    $_SESSION['error'] =
        "Please complete all required fields.";

    header("Location: edit_plan.php?id=".$id);

    exit();

}


if ($duration < 1) {

    $_SESSION['error'] =
        "Duration must be at least 1 month.";

    header("Location: edit_plan.php?id=".$id);

    exit();

}


if ($start_month < 1 || $start_month > 12) {

    $_SESSION['error'] =
        "Invalid start month.";

    header("Location: edit_plan.php?id=".$id);

    exit();

}


if ($start_year < 2025) {

    $_SESSION['error'] =
        "Invalid start year.";

    header("Location: edit_plan.php?id=".$id);

    exit();

}


/*
|--------------------------------------------------------------------------
| Image
|--------------------------------------------------------------------------
*/

$newImage = $plan['plan_image'];

$oldImage = $plan['plan_image'];


if (
    isset($_FILES['plan_image']) &&
    $_FILES['plan_image']['error'] !== UPLOAD_ERR_NO_FILE
) {

    $image = $_FILES['plan_image'];


    /*
    Upload error
    */

    if ($image['error'] !== UPLOAD_ERR_OK) {

        $_SESSION['error'] =
            "There was a problem uploading the image.";

        header("Location: edit_plan.php?id=".$id);

        exit();

    }


    /*
    5MB limit
    */

    if ($image['size'] > 5 * 1024 * 1024) {

        $_SESSION['error'] =
            "Image must not exceed 5MB.";

        header("Location: edit_plan.php?id=".$id);

        exit();

    }


    /*
    Verify actual image
    */

    $imageInfo =
        getimagesize($image['tmp_name']);


    if ($imageInfo === false) {

        $_SESSION['error'] =
            "Please upload a valid image.";

        header("Location: edit_plan.php?id=".$id);

        exit();

    }


    $allowedTypes = [

        'image/jpeg',
        'image/png',
        'image/webp'

    ];


    if (
        !in_array(
            $imageInfo['mime'],
            $allowedTypes,
            true
        )
    ) {

        $_SESSION['error'] =
            "Only JPG, PNG and WEBP images are allowed.";

        header("Location: edit_plan.php?id=".$id);

        exit();

    }


    /*
    Upload directory
    */

    $uploadDir =
        "../assets/uploads/plans/";


    if (!is_dir($uploadDir)) {

        mkdir(
            $uploadDir,
            0755,
            true
        );

    }


    /*
    Extension
    */

    $extension = match (
        $imageInfo['mime']
    ) {

        'image/jpeg' => 'jpg',

        'image/png' => 'png',

        'image/webp' => 'webp',

        default => 'jpg'

    };


    /*
    New filename
    */

    $newImage =
        'plan_' .
        time() .
        '_' .
        bin2hex(
            random_bytes(5)
        ) .
        '.' .
        $extension;


    $destination =
        $uploadDir . $newImage;


    /*
    Move image
    */

    if (
        !move_uploaded_file(
            $image['tmp_name'],
            $destination
        )
    ) {

        $_SESSION['error'] =
            "Unable to save the new image.";

        header("Location: edit_plan.php?id=".$id);

        exit();

    }

}


/*
|--------------------------------------------------------------------------
| Update Database
|--------------------------------------------------------------------------
*/

try {

    $pdo->beginTransaction();


    $sql = "

        UPDATE plans

        SET

            plan_name=?,
            plan_type=?,
            amount=?,
            frequency=?,
            duration=?,
            description=?,
            plan_image=?,
            package_items=?,
            start_month=?,
            start_year=?,
            status=?

        WHERE id=?

    ";


    $stmt =
        $pdo->prepare($sql);


    $stmt->execute([

        $plan_name,
        $plan_type,
        $amount,
        $frequency,
        $duration,
        $description,
        $newImage,
        $package_items,
        $start_month,
        $start_year,
        $status,
        $id

    ]);


    $pdo->commit();


    /*
    |--------------------------------------------------------------------------
    | Delete old image
    |--------------------------------------------------------------------------
    */

    if (
        $oldImage &&
        $newImage !== $oldImage
    ) {

        $oldImagePath =
            "../assets/uploads/plans/" .
            $oldImage;


        if (
            file_exists(
                $oldImagePath
            )
        ) {

            unlink(
                $oldImagePath
            );

        }

    }


    $_SESSION['success'] =
        "Scheme updated successfully.";


    header("Location: plans.php");

    exit();


} catch (Exception $e) {


    /*
    Rollback
    */

    if (
        $pdo->inTransaction()
    ) {

        $pdo->rollBack();

    }


    /*
    Delete newly uploaded image
    if database update failed
    */

    if (
        $newImage &&
        $newImage !== $oldImage
    ) {

        $newImagePath =
            "../assets/uploads/plans/" .
            $newImage;


        if (
            file_exists(
                $newImagePath
            )
        ) {

            unlink(
                $newImagePath
            );

        }

    }


    $_SESSION['error'] =
        "Scheme update failed. Please try again.";


    header(
        "Location: edit_plan.php?id=".$id
    );

    exit();

}