<?php
/**
 * ADMIN: REJECT NEW ITEM
 * File: admin/item-reject.php
 *
 * GET  → shows a confirmation form so admin can enter a rejection reason
 * POST → rejects the item and sends the vendor a notification email
 */

require_once '../app/Core/init.php';
require_once '../app/Core/Mailer.php';

Auth::requireAdmin();

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

if ($item_id <= 0) {
    flash('error', 'Invalid item ID.', 'danger');
    redirect('items.php');
}

$db = Database::getInstance();

// ── GET: show confirmation + reason form ─────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    $item_data = $db->fetch("
        SELECT i.id, i.title, i.approval_status,
               v.business_name AS vendor_name
        FROM items i
        JOIN vendors v ON i.vendor_id = v.id
        WHERE i.id = ?
    ", [$item_id]);

    if (!$item_data) {
        flash('error', 'Item not found.', 'danger');
        redirect('items.php');
    }

    $page_title  = "Reject Item";
    $active_menu = "items";
    include '../templates/layouts/admin/head.php';
    ?>
    <div class="main-content">
        <?php include '../templates/layouts/admin/header.php'; ?>
        <div class="content" style="max-width:620px; margin:30px auto;">
            <div class="card shadow-sm">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="fas fa-times-circle"></i> Reject Item Listing</h5>
                </div>
                <div class="card-body">
                    <p class="mb-3">You are about to <strong>reject</strong> the following item listing. The vendor will be notified by email.</p>

                    <div class="alert alert-warning">
                        <strong><?= htmlspecialchars($item_data['title']) ?></strong><br>
                        <small class="text-muted">by <?= htmlspecialchars($item_data['vendor_name']) ?></small>
                    </div>

                    <form method="POST" action="item-reject.php">
                        <input type="hidden" name="id" value="<?= $item_id ?>">

                        <div class="mb-3">
                            <label class="form-label fw-bold">
                                Reason for Rejection
                                <span class="text-muted fw-normal">(recommended — this is sent to the vendor)</span>
                            </label>
                            <textarea name="reason" class="form-control" rows="4"
                                      placeholder="e.g. Photos are unclear, description is incomplete, item category is wrong..."></textarea>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-danger">
                                <i class="fas fa-times"></i> Confirm Rejection
                            </button>
                            <a href="items.php" class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php
    include '../templates/layouts/admin/footer.php';
    exit;
}

// ── POST: process the rejection ──────────────────────────────────────
$reason = trim($_POST['reason'] ?? '');

try {
    // 1. Fetch item + vendor contact details
    $item_data = $db->fetch("
        SELECT
            i.id,
            i.title,
            i.approval_status,
            v.business_name AS vendor_name,
            u.email         AS vendor_email
        FROM items i
        JOIN vendors v ON i.vendor_id = v.id
        JOIN users   u ON v.user_id   = u.id
        WHERE i.id = ?
    ", [$item_id]);

    if (!$item_data) {
        throw new Exception('Item not found.');
    }

    if ($item_data['approval_status'] === 'rejected') {
        flash('info', 'This item has already been rejected.', 'info');
        redirect('items.php');
    }

    // 2. Update approval status in DB
    $db->execute("
        UPDATE items
        SET approval_status = 'rejected',
            updated_at      = NOW()
        WHERE id = ?
    ", [$item_id]);

    // 3. Send branded email to vendor
    $mailer = new Mailer();
    $sent   = $mailer->sendItemRejected(
        $item_data['vendor_email'],
        $item_data['vendor_name'],
        $item_data['title'],
        $reason ?: 'No specific reason was provided. Please contact support for more information.'
    );

    if (!$sent) {
        log_message("Item rejection email failed — item #{$item_id} to {$item_data['vendor_email']}", 'warning');
    }

    flash('success', 'Item <strong>' . htmlspecialchars($item_data['title']) . '</strong> rejected. Vendor notified by email.', 'success');

} catch (Exception $e) {
    log_message('item-reject error: ' . $e->getMessage(), 'error');
    flash('error', 'Error: ' . $e->getMessage(), 'danger');
}

redirect('items.php');