<?php
/**
 * ADMIN: APPROVE NEW ITEM
 * File: admin/item-approve.php
 *
 * Called via <a href="item-approve.php?id=X"> from items.php (GET request).
 * Approves the item, sends vendor a notification email.
 */

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

Auth::requireAdmin();

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

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

$db = Database::getInstance();

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'] === 'approved') {
        flash('info', 'This item is already approved.', 'info');
        redirect('items.php');
    }

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

    // 3. Send branded email to vendor
    $mailer = new Mailer();
    $sent   = $mailer->sendItemApproved(
        $item_data['vendor_email'],
        $item_data['vendor_name'],
        $item_data['title']
    );

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

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

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

redirect('items.php');