<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/supplies.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/settings.php';

$user = sparrow_require_backyard_login();
$pdo = sparrow_db();

$supply_settings = sparrow_get_settings($pdo, [
    'supplier_names',
]);

$supplier_names = array_values(array_unique(array_filter(array_map(
    'trim',
    preg_split(
        '/\r\n|\r|\n/',
        $supply_settings['supplier_names'] ?? ''
    ) ?: []
))));

if (!$supplier_names) {
    $supplier_names = [
        'Jiffy',
        'ShirtSpace',
        'Texas Vinyl Supply',
        'Amazon',
        'Other',
    ];
}

$notice = '';
$error = '';
$editing_id = max(0, (int) ($_GET['edit'] ?? 0));
$has_form_error = false;

$form_data = [
    'supply_id' => 0,
    'name' => '',
    'category' => '',
    'quantity' => '0',
    'reorder_level' => '0',
    'unit' => '',
    'supplier' => '',
    'unit_cost' => '',
    'notes' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
	
	    if ($action === 'delete_supply') {
        $delete_id = max(
            0,
            (int) ($_POST['supply_id'] ?? 0)
        );

        try {
            sparrow_delete_supply($delete_id);

            header('Location: supplies.php?deleted=1');
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
	
	    if ($action === 'quick_adjust') {
        $adjust_id = max(
            0,
            (int) ($_POST['supply_id'] ?? 0)
        );

        $quick_choice = (string) (
            $_POST['quick_amount'] ?? ''
        );

        $quick_options = [
            '-1' => [
                'amount' => -1.0,
                'type' => 'Used',
                'note' => 'Quick -1 adjustment.',
            ],
            '1' => [
                'amount' => 1.0,
                'type' => 'Restock',
                'note' => 'Quick +1 adjustment.',
            ],
			'-10' => [
                'amount' => -10.0,
                'type' => 'Used',
                'note' => 'Quick -10 adjustment.',
            ],
            '10' => [
                'amount' => 10.0,
                'type' => 'Restock',
                'note' => 'Quick +10 adjustment.',
            ],
        ];

        try {
            if (!isset($quick_options[$quick_choice])) {
                throw new InvalidArgumentException(
                    'Choose a valid quantity adjustment.'
                );
            }

            $quick_adjustment =
                $quick_options[$quick_choice];

            sparrow_adjust_supply(
                $adjust_id,
                $quick_adjustment['amount'],
                $quick_adjustment['type'],
                $quick_adjustment['note']
            );

            header(
                'Location: supplies.php?adjusted=1'
            );
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }

    if ($action === 'save_supply') {
        $editing_id = max(
            0,
            (int) ($_POST['supply_id'] ?? 0)
        );

        $form_data = [
            'supply_id' => $editing_id,
            'name' => trim($_POST['name'] ?? ''),
            'category' => trim(
                $_POST['category'] ?? ''
            ),
            'quantity' => trim(
                $_POST['quantity'] ?? '0'
            ),
            'reorder_level' => trim(
                $_POST['reorder_level'] ?? '0'
            ),
            'unit' => trim($_POST['unit'] ?? ''),
            'supplier' => trim(
                $_POST['supplier'] ?? ''
            ),
            'unit_cost' => trim(
                $_POST['unit_cost'] ?? ''
            ),
            'notes' => trim($_POST['notes'] ?? ''),
        ];

        try {
            sparrow_save_supply($form_data);

            if ($editing_id > 0) {
                header('Location: supplies.php?updated=1');
            } else {
                header('Location: supplies.php?added=1');
            }

            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
            $has_form_error = true;
        }
    }
}

if (isset($_GET['added'])) {
    $notice = 'Supply item added successfully.';
} elseif (isset($_GET['updated'])) {
    $notice = 'Supply item updated successfully.';
} elseif (isset($_GET['deleted'])) {
    $notice = 'Supply item deleted successfully.';
} elseif (isset($_GET['adjusted'])) {
    $notice = 'Supply quantity updated successfully.';
}

$supplies = sparrow_get_supplies();
$low_supplies = sparrow_get_low_supplies();

if ($editing_id > 0 && !$has_form_error) {
    $editing_supply = null;

    foreach ($supplies as $supply) {
        if ((int) $supply['id'] === $editing_id) {
            $editing_supply = $supply;
            break;
        }
    }

    if ($editing_supply === null) {
        $error = 'Supply item could not be found.';
        $editing_id = 0;
    } else {
        $form_data = [
            'supply_id' => $editing_id,
            'name' => $editing_supply['name'],
            'category' => $editing_supply['category'] ?? '',
            'quantity' => $editing_supply['quantity'],
            'reorder_level' => $editing_supply['reorder_level'],
            'unit' => $editing_supply['unit'] ?? '',
            'supplier' => $editing_supply['supplier'] ?? '',
            'unit_cost' => $editing_supply['unit_cost'] ?? '',
            'notes' => $editing_supply['notes'] ?? '',
        ];
    }
}

sparrow_backyard_header('Supplies / Inventory');
?>

<section class="card">
    <h1>Supplies / Inventory</h1>

    <p class="muted">
        Track supplies, quantities, reorder levels,
        and inventory changes.
    </p>

    <?php if ($notice !== ''): ?>
        <div class="notice success">
            <?php echo sparrow_escape($notice); ?>
        </div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
        <div class="notice error">
            <?php echo sparrow_escape($error); ?>
        </div>
    <?php endif; ?>
</section>

<div class="supplies-page-layout">

    <div class="supplies-left-column">

        <section class="card supplies-form-card">
            <h2>
                <?php echo $editing_id > 0
                    ? 'Edit Supply'
                    : 'Add Supply'; ?>
            </h2>

            <form method="post" class="form-grid">
                <input
                    type="hidden"
                    name="action"
                    value="save_supply"
                >

                <input
                    type="hidden"
                    name="supply_id"
                    value="<?php echo $editing_id; ?>"
                >

                <div class="field field-full">
                    <label for="supply-name">
                        Supply Name
                    </label>

                    <input
                        type="text"
                        name="name"
                        id="supply-name"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['name']
                        );
                        ?>"
                        required
                    >
                </div>

                <div class="field">
                    <label for="supply-category">
                        Category
                    </label>

                    <input
                        type="text"
                        name="category"
                        id="supply-category"
                        list="supply-categories"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['category']
                        );
                        ?>"
                        placeholder="Example: Shirts"
                    >

                    <datalist id="supply-categories">
                        <option value="Shirts">
                        <option value="Koozies">
                        <option value="Pens">
                        <option value="Vinyl">
                        <option value="DTF Prints">
                        <option value="Packaging">
                        <option value="Other">
                    </datalist>
                </div>

                <div class="field">
                    <label for="supply-unit">
                        Unit
                    </label>

                    <input
                        type="text"
                        name="unit"
                        id="supply-unit"
                        list="supply-units"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['unit']
                        );
                        ?>"
                        placeholder="Example: each"
                    >

                    <datalist id="supply-units">
                        <option value="each">
                        <option value="shirts">
                        <option value="rolls">
                        <option value="sheets">
                        <option value="feet">
                        <option value="yards">
                        <option value="packs">
                        <option value="boxes">
                    </datalist>
                </div>

                <div class="field">
                    <label for="supply-quantity">
                        <?php echo $editing_id > 0
                            ? 'Current Quantity'
                            : 'Starting Quantity'; ?>
                    </label>

                    <input
                        type="number"
                        name="quantity"
                        id="supply-quantity"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['quantity']
                        );
                        ?>"
                        min="0"
                        step="0.01"
                        required
                    >
                </div>

                <div class="field">
                    <label for="supply-reorder-level">
                        Reorder Level
                    </label>

                    <input
                        type="number"
                        name="reorder_level"
                        id="supply-reorder-level"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['reorder_level']
                        );
                        ?>"
                        min="0"
                        step="0.01"
                    >
                </div>

                <div class="field">
                    <label for="supply-supplier">
                        Supplier
                    </label>

                    <input
                        type="text"
                        name="supplier"
                        id="supply-supplier"
                        list="supply-suppliers"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['supplier']
                        );
                        ?>"
                        placeholder="Optional"
                    >

                    <datalist id="supply-suppliers">
                        <?php foreach (
                            $supplier_names as $supplier_name
                        ): ?>
                            <option value="<?php
                            echo sparrow_escape($supplier_name);
                            ?>">
                        <?php endforeach; ?>
                    </datalist>
                </div>

                <div class="field">
                    <label for="supply-unit-cost">
                        Unit Cost
                    </label>

                    <input
                        type="number"
                        name="unit_cost"
                        id="supply-unit-cost"
                        value="<?php
                        echo sparrow_escape(
                            $form_data['unit_cost']
                        );
                        ?>"
                        min="0"
                        step="0.01"
                        placeholder="Optional"
                    >
                </div>

                <div class="field field-full">
                    <label for="supply-notes">
                        Notes
                    </label>

                    <textarea
                        name="notes"
                        id="supply-notes"
                        rows="4"
                    ><?php
                    echo sparrow_escape(
                        $form_data['notes']
                    );
                    ?></textarea>
                </div>

                <div class="field field-full">
                    <button type="submit" class="button">
                        <?php echo $editing_id > 0
                            ? 'Save Changes'
                            : 'Add Supply'; ?>
                    </button>

                    <?php if ($editing_id > 0): ?>
                        <a href="supplies.php" class="button">
                            Cancel
                        </a>
                    <?php endif; ?>
                </div>
            </form>
        </section>

    </div>

<div class="supplies-right-column">
	
	        <section class="card supplies-summary-card">
            <h2>Inventory Summary</h2>

            <div class="supplies-summary-numbers">
                <div>
                    <span class="summary-number">
                        <?php echo count($supplies); ?>
                    </span>

                    <span class="muted">
                        Active Supplies
                    </span>
                </div>

                <div>
                    <span class="summary-number low-number">
                        <?php echo count($low_supplies); ?>
                    </span>

                    <span class="muted">
                        Low Stock
                    </span>
                </div>
            </div>

            <?php if ($low_supplies): ?>
                <div class="low-stock-list">
                    <h3>Low-Stock Items</h3>

                    <?php foreach (
                        $low_supplies as $supply
                    ): ?>
                        <div class="low-stock-item">
                            <strong>
                                <?php
                                echo sparrow_escape(
                                    $supply['name']
                                );
                                ?>
                            </strong>

                            <span>
                                <?php
                                echo number_format(
                                    (float) $supply['quantity'],
                                    2
                                );
                                ?>

                                <?php
                                echo sparrow_escape(
                                    $supply['unit']
                                );
                                ?>
                                remaining
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="muted">
                    No supplies are currently at or below
                    their reorder level.
                </p>
            <?php endif; ?>
        </section>
		
		    <section class="card supplies-inventory-card">
        <h2>Current Inventory</h2>

        <?php if (!$supplies): ?>
            <p class="muted">
                No supplies have been added yet.
            </p>
        <?php else: ?>
            <div class="table-wrap">
                <table class="supplies-table">
                    <thead>
                        <tr>
                            <th>Supply</th>
                            <th>Category</th>
                            <th>Quantity</th>
                            <th>Reorder At</th>
                            <th>Supplier</th>
                            <th>Unit Cost</th>
                            <th>Notes</th>
                            <th>Actions</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach (
                            $supplies as $supply
                        ): ?>
                            <?php
                            $is_low = (
                                (float) $supply['reorder_level'] > 0
                                && (float) $supply['quantity']
                                    <= (float) $supply[
                                        'reorder_level'
                                    ]
                            );
                            ?>

                            <tr class="<?php
                            echo $is_low
                                ? 'supply-row-low'
                                : '';
                            ?>">
                                <td data-label="Supply">
                                    <strong>
                                        <?php
                                        echo sparrow_escape(
                                            $supply['name']
                                        );
                                        ?>
                                    </strong>

                                    <?php if ($is_low): ?>
                                        <span
                                            class="
                                                status-pill
                                                low-pill
                                            "
                                        >
                                            Low
                                        </span>
                                    <?php endif; ?>
                                </td>

                                <td data-label="Category">
                                    <?php
                                    if (
                                        $supply['category'] !== ''
                                    ) {
                                        echo sparrow_escape(
                                            $supply['category']
                                        );
                                    } else {
                                        echo '<span class="muted">'
                                            . '—'
                                            . '</span>';
                                    }
                                    ?>
                                </td>

                                <td data-label="Quantity">
                                    <strong>
                                        <?php
                                        echo number_format(
                                            (float) $supply[
                                                'quantity'
                                            ],
                                            2
                                        );
                                        ?>
                                    </strong>

                                    <?php
                                    echo sparrow_escape(
                                        $supply['unit']
                                    );
                                    ?>
                                </td>

                                <td data-label="Reorder At">
                                    <?php
                                    echo number_format(
                                        (float) $supply[
                                            'reorder_level'
                                        ],
                                        2
                                    );
                                    ?>

                                    <?php
                                    echo sparrow_escape(
                                        $supply['unit']
                                    );
                                    ?>
                                </td>

                                <td data-label="Supplier">
                                    <?php
                                    if (
                                        $supply['supplier'] !== ''
                                    ) {
                                        echo sparrow_escape(
                                            $supply['supplier']
                                        );
                                    } else {
                                        echo '<span class="muted">'
                                            . '—'
                                            . '</span>';
                                    }
                                    ?>
                                </td>

                                <td data-label="Unit Cost">
                                    <?php if (
                                        $supply['unit_cost'] !== null
                                    ): ?>
                                        $<?php
                                        echo number_format(
                                            (float) $supply[
                                                'unit_cost'
                                            ],
                                            2
                                        );
                                        ?>
                                    <?php else: ?>
                                        <span class="muted">—</span>
                                    <?php endif; ?>
                                </td>

                                <td data-label="Notes">
                                    <?php
                                    if ($supply['notes'] !== '') {
                                        echo nl2br(
                                            sparrow_escape(
                                                $supply['notes']
                                            )
                                        );
                                    } else {
                                        echo '<span class="muted">'
                                            . '—'
                                            . '</span>';
                                    }
                                    ?>
                                </td>

                                <td data-label="Actions">
								<div class="supply-quick-controls">
    <?php foreach (
        [
            '-1' => '−1',
            '1' => '+1',
			'-10' => '-10',
            '10' => '+10',
        ] as $amount => $label
    ): ?>
        <form method="post">
            <input
                type="hidden"
                name="action"
                value="quick_adjust"
            >

            <input
                type="hidden"
                name="supply_id"
                value="<?php
                echo (int) $supply['id'];
                ?>"
            >

            <input
                type="hidden"
                name="quick_amount"
                value="<?php
                echo sparrow_escape($amount);
                ?>"
            >

            <button
                type="submit"
                class="button supply-quick-button"
                aria-label="<?php
                echo sparrow_escape(
                    $label
                    . ' '
                    . $supply['name']
                );
                ?>"
            >
                <?php echo sparrow_escape($label); ?>
            </button>
        </form>
    <?php endforeach; ?>
</div>
                                    <a
                                        href="supplies.php?edit=<?php
                                        echo (int) $supply['id'];
                                        ?>"
                                        class="button"
                                    >
                                        Edit
                                    </a>
									<form
    method="post"
    class="supply-delete-form"
    onsubmit="return confirm(
        'Permanently delete this supply and its adjustment history?'
    );"
>
    <input
        type="hidden"
        name="action"
        value="delete_supply"
    >

    <input
        type="hidden"
        name="supply_id"
        value="<?php echo (int) $supply['id']; ?>"
    >

    <button
        type="submit"
        class="button supply-delete-button"
    >
        Delete
    </button>
</form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
</div>
</div>

<?php sparrow_backyard_footer(); ?>
