<?php
session_start();
require_once("definitions.php");

header('Content-Type: application/json');

$store_key = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;
if ($store_key === 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store key']);
    exit;
}

$plan_key = isset($_POST['plan_key']) ? intval($_POST['plan_key']) : 0;

// Required fields
$name = trim($_POST['name'] ?? '');
$mailbox_attribute_key = isset($_POST['mailbox_attribute_key']) ? intval($_POST['mailbox_attribute_key']) : 0;
$web_viewable = isset($_POST['web_viewable']) && ($_POST['web_viewable'] == '1' || $_POST['web_viewable'] === 'on') ? 1 : 0;

$pkglimit_mo = isset($_POST['pkglimit_mo']) ? intval($_POST['pkglimit_mo']) : 0;
$pkglimit_instant = isset($_POST['pkglimit_instant']) ? intval($_POST['pkglimit_instant']) : 0;

$occupant_limit = isset($_POST['occupant_limit']) ? intval($_POST['occupant_limit']) : 0;
$additional_occupants_fee = isset($_POST['additional_occupants_fee']) ? floatval($_POST['additional_occupants_fee']) : 0.0;

$package_limit = isset($_POST['package_limit']) ? intval($_POST['package_limit']) : 0;

$price_1mo = isset($_POST['price_1mo']) ? floatval($_POST['price_1mo']) : 0.0;
$price_3mo = isset($_POST['price_3mo']) ? floatval($_POST['price_3mo']) : 0.0;
$price_6mo = isset($_POST['price_6mo']) ? floatval($_POST['price_6mo']) : 0.0;
$price_12mo = isset($_POST['price_12mo']) ? floatval($_POST['price_12mo']) : 0.0;

$free_months_1mo = isset($_POST['free_months_1mo']) ? intval($_POST['free_months_1mo']) : 0;
$free_months_3mo = isset($_POST['free_months_3mo']) ? intval($_POST['free_months_3mo']) : 0;
$free_months_6mo = isset($_POST['free_months_6mo']) ? intval($_POST['free_months_6mo']) : 0;
$free_months_12mo = isset($_POST['free_months_12mo']) ? intval($_POST['free_months_12mo']) : 0;

$categories = [
    'incoming_mail_items',
    'open_scan_requests',
    'scanned_pages_per_month',
    'scanned_pages_per_request',
    'forward_requests',
    'check_deposit_requests',
    'recycle_requests',
    'shred_requests',
];

$allowances = [];
$extra_fees = [];

foreach ($categories as $cat) {
    $allowances[$cat] = isset($_POST[$cat . '_allowance']) ? intval($_POST[$cat . '_allowance']) : 0;
    $extra_fees[$cat] = isset($_POST[$cat . '_extra_fee']) ? floatval($_POST[$cat . '_extra_fee']) : 0.0;
}

$visit_limit_per_month = isset($_POST['visit_limit_per_month']) ? intval($_POST['visit_limit_per_month']) : 0;

// Fix name: cost_per_extra_visit in DB vs cost_per_visit in form/PHP
$cost_per_extra_visit = isset($_POST['cost_per_visit']) ? floatval($_POST['cost_per_visit']) : 0.0;

$local_pickup = isset($_POST['local_pickup']) && ($_POST['local_pickup'] == '1' || $_POST['local_pickup'] === 'on') ? 1 : 0;

// The DB has order and businesses columns which are NOT NULL and missing in form.
// Since form cannot be changed, set default values here:
$order = 0;        // default value for order field
$businesses = 0;   // default value for businesses field

if ($name === '') {
    echo json_encode(['success' => false, 'message' => 'Plan name is required']);
    exit;
}

if ($mailbox_attribute_key === 0) {
    echo json_encode(['success' => false, 'message' => 'Mailbox Type is required']);
    exit;
}

$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

if ($plan_key > 0) {
    // Update existing plan
    $sql = "UPDATE mailbox_plans SET
        store_key = ?,
        mailbox_attribute_key = ?,
        name = ?,
        `order` = ?,
        businesses = ?,
        occupant_limit = ?,
        additional_occupants_fee = ?,
        package_limit = ?,
        pkglimit_mo = ?,
        pkglimit_instant = ?,
        price_1mo = ?,
        price_3mo = ?,
        price_6mo = ?,
        price_12mo = ?,
        free_months_1mo = ?,
        free_months_3mo = ?,
        free_months_6mo = ?,
        free_months_12mo = ?,
        webviewable = ?,
        incoming_mail_items_allowance = ?,
        incoming_mail_items_extra_fee = ?,
        open_scan_requests_allowance = ?,
        open_scan_requests_extra_fee = ?,
        scanned_pages_per_month_allowance = ?,
        scanned_pages_per_month_extra_fee = ?,
        scanned_pages_per_request_allowance = ?,
        scanned_pages_per_request_extra_fee = ?,
        forward_requests_allowance = ?,
        forward_requests_extra_fee = ?,
        check_deposit_requests_allowance = ?,
        check_deposit_requests_extra_fee = ?,
        recycle_requests_allowance = ?,
        recycle_requests_extra_fee = ?,
        shred_requests_allowance = ?,
        shred_requests_extra_fee = ?,
        visit_limit_per_month = ?,
        cost_per_extra_visit = ?,
        local_pickup = ?
        WHERE plan_key = ? AND store_key = ?";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    // Bind param types and variables:
    // Types: i = integer, d = double (float), s = string
    $stmt->bind_param(
        "iisiiidiiiddddiiiiidididididididididiiii",
        $store_key,
        $mailbox_attribute_key,
        $name,
        $order,
        $businesses,
        $occupant_limit,
        $additional_occupants_fee,
        $package_limit,
        $pkglimit_mo,
        $pkglimit_instant,
        $price_1mo,
        $price_3mo,
        $price_6mo,
        $price_12mo,
        $free_months_1mo,
        $free_months_3mo,
        $free_months_6mo,
        $free_months_12mo,
        $web_viewable,
        $allowances['incoming_mail_items'],
        $extra_fees['incoming_mail_items'],
        $allowances['open_scan_requests'],
        $extra_fees['open_scan_requests'],
        $allowances['scanned_pages_per_month'],
        $extra_fees['scanned_pages_per_month'],
        $allowances['scanned_pages_per_request'],
        $extra_fees['scanned_pages_per_request'],
        $allowances['forward_requests'],
        $extra_fees['forward_requests'],
        $allowances['check_deposit_requests'],
        $extra_fees['check_deposit_requests'],
        $allowances['recycle_requests'],
        $extra_fees['recycle_requests'],
        $allowances['shred_requests'],
        $extra_fees['shred_requests'],
        $visit_limit_per_month,
        $cost_per_extra_visit,
        $local_pickup,
        $plan_key,
        $store_key
    );

    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Execute failed: ' . $stmt->error]);
    }
    $stmt->close();
} else {
    // Insert new plan
    $sql = "INSERT INTO mailbox_plans (
        store_key,
        mailbox_attribute_key,
        name,
        `order`,
        businesses,
        occupant_limit,
        additional_occupants_fee,
        package_limit,
        pkglimit_mo,
        pkglimit_instant,
        price_1mo,
        price_3mo,
        price_6mo,
        price_12mo,
        free_months_1mo,
        free_months_3mo,
        free_months_6mo,
        free_months_12mo,
        webviewable,
        incoming_mail_items_allowance,
        incoming_mail_items_extra_fee,
        open_scan_requests_allowance,
        open_scan_requests_extra_fee,
        scanned_pages_per_month_allowance,
        scanned_pages_per_month_extra_fee,
        scanned_pages_per_request_allowance,
        scanned_pages_per_request_extra_fee,
        forward_requests_allowance,
        forward_requests_extra_fee,
        check_deposit_requests_allowance,
        check_deposit_requests_extra_fee,
        recycle_requests_allowance,
        recycle_requests_extra_fee,
        shred_requests_allowance,
        shred_requests_extra_fee,
        visit_limit_per_month,
        cost_per_extra_visit,
        local_pickup
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
        $conn->close();
        exit;
    }

    $stmt->bind_param(
        "iisiiidiiiddddiiiiidididididididididii",
        $store_key,
        $mailbox_attribute_key,
        $name,
        $order,
        $businesses,
        $occupant_limit,
        $additional_occupants_fee,
        $package_limit,
        $pkglimit_mo,
        $pkglimit_instant,
        $price_1mo,
        $price_3mo,
        $price_6mo,
        $price_12mo,
        $free_months_1mo,
        $free_months_3mo,
        $free_months_6mo,
        $free_months_12mo,
        $web_viewable,
        $allowances['incoming_mail_items'],
        $extra_fees['incoming_mail_items'],
        $allowances['open_scan_requests'],
        $extra_fees['open_scan_requests'],
        $allowances['scanned_pages_per_month'],
        $extra_fees['scanned_pages_per_month'],
        $allowances['scanned_pages_per_request'],
        $extra_fees['scanned_pages_per_request'],
        $allowances['forward_requests'],
        $extra_fees['forward_requests'],
        $allowances['check_deposit_requests'],
        $extra_fees['check_deposit_requests'],
        $allowances['recycle_requests'],
        $extra_fees['recycle_requests'],
        $allowances['shred_requests'],
        $extra_fees['shred_requests'],
        $visit_limit_per_month,
        $cost_per_extra_visit,
        $local_pickup
    );

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'plan_key' => $stmt->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Execute failed: ' . $stmt->error]);
    }
    $stmt->close();
}

$conn->close();