<?php
/**
 * ADMIN: REJECT ITEM UPDATE
 * File: admin/item-update-reject.php
 *
 * Rejects a vendor's pending item-edit request and notifies
 * the vendor by email using the branded template.
 */

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

Auth::requireAdmin();

$update_id = (int)($_REQUEST['id'] ?? 0);
$confirm   = isset($_REQUEST['confirm']) || $_SERVER['REQUEST_METHOD'] === 'POST';

if ($update_id <= 0 || !$confirm) {
    flash('error', 'Invalid request — missing confirmation.', 'danger');
    redirect('updated-items.php');
}

$reason = trim($_POST['reason'] ?? $_GET['reason'] ?? '');
$item   = new Item();
$db     = Database::getInstance();

try {
    // ── 1. Load update record ────────────────────────────────────────
    $update = $item->getUpdate($update_id);

    if (!$update) {
        throw new Exception('Update record not found.');
    }

    if ($update['approval_status'] !== 'pending') {
        throw new Exception('This update has already been ' . $update['approval_status'] . '.');
    }

    // ── 2. Reject the update ─────────────────────────────────────────
    $result = $item->rejectUpdate($update_id, Auth::id());

    if (!$result) {
        throw new Exception('Failed to reject update.');
    }

    // ── 3. Send email to vendor ──────────────────────────────────────
    $vendor_email = $update['vendor_email'] ?? null;
    $vendor_name  = $update['vendor_name']  ?? null;

    if (!$vendor_email) {
        $vendor_row   = $db->fetch("
            SELECT 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 = ?
        ", [$update['item_id']]);
        $vendor_email = $vendor_row['vendor_email'] ?? null;
        $vendor_name  = $vendor_row['vendor_name']  ?? 'Vendor';
    }

    if ($vendor_email) {
        $mailer    = new Mailer();
        $mail_sent = $mailer->sendItemUpdateRejected([
            'vendor_name'  => $vendor_name,
            'vendor_email' => $vendor_email,
            'item_id'      => $update['item_id'],
            'item_title'   => $update['title'] ?? 'your item',
            'reason'       => $reason ?: 'No specific reason provided.',
            'app_name'     => APP_NAME,
            'app_url'      => APP_URL,
        ]);

        if (!$mail_sent) {
            log_message("Item-update rejection email failed for update #{$update_id} ({$vendor_email})", 'warning');
        }
    }

    flash('success', 'Item update rejected successfully and vendor notified.', 'success');

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

redirect('updated-items.php');