<?php

session_start();

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


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

    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;
$description = trim($_POST['description'] ?? '');
$package_items = trim($_POST['package_items'] ?? '');
$start_month = !empty($_POST['start_month']) ? (int)$_POST['start_month'] : null;
$start_year = !empty($_POST['start_year']) ? (int)$_POST['start_year'] : null;
$status = trim($_POST['status'] ?? 'active');


/*
|--------------------------------------------------------------------------
| Validate Required Fields
|--------------------------------------------------------------------------
*/

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

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

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

}


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

if ($duration < 1) {

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

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

}


/*
|--------------------------------------------------------------------------
| Validate Start Month
|--------------------------------------------------------------------------
*/

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

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

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

}


/*
|--------------------------------------------------------------------------
| Validate Start Year
|--------------------------------------------------------------------------
*/

if ($start_year < 2025) {

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

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

}


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

$plan_image = null;

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

    $image = $_FILES['plan_image'];

    /*
    Check upload error
    */

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

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

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

    }


    /*
    Maximum size = 5MB
    */

    $maxSize = 5 * 1024 * 1024;

    if ($image['size'] > $maxSize) {

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

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

    }


    /*
    Check actual image type
    */

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

    if ($imageInfo === false) {

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

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

    }


    /*
    Allowed image types
    */

    $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: add_plan.php");
        exit();

    }


    /*
    Create upload folder if it doesn't exist
    */

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

    if (!is_dir($uploadDir)) {

        mkdir($uploadDir, 0755, true);

    }


    /*
    Generate safe unique filename
    */

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

        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',

        default => 'jpg'

    };


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


    $destination = $uploadDir . $filename;


    /*
    Move image
    */

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

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

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

    }


    /*
    Save only the relative filename
    */

    $plan_image = $filename;

}


/*
|--------------------------------------------------------------------------
| Save Plan
|--------------------------------------------------------------------------
*/

try {

    $sql = "
        INSERT INTO plans
        (
            plan_name,
            plan_type,
            amount,
            frequency,
            duration,
            description,
            plan_image,
            package_items,
            start_month,
            start_year,
            status
        )
        VALUES
        (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )
    ";


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


    $stmt->execute([

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

    ]);


    /*
    Success
    */

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


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


} catch (Exception $e) {


    /*
    If database saving fails after image upload,
    remove the uploaded image so we don't leave
    unused files behind.
    */

    if ($plan_image !== null) {

        $uploadedFile =
            "../assets/uploads/plans/" . $plan_image;

        if (file_exists($uploadedFile)) {

            unlink($uploadedFile);

        }

    }


    $_SESSION['error'] =
        "Unable to create scheme. Please try again.";

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

}