<?php
/**
 * ADMIN: APPROVE ITEM UPDATE
 * File: admin/item-update-approve.php
 *
 * Approves a vendor's pending item-edit request and notifies the vendor by email.
 * Called via POST form from item-update-review.php.
 */

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.', 'danger');
    redirect('updated-items.php');
}

$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. Apply the update via Item model
    $result = $item->approveUpdate($update_id, Auth::id());

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

    // 3. Get vendor email — from update record if available, otherwise from DB
    $vendor_email = $update['vendor_email'] ?? null;
    $vendor_name  = $update['vendor_name']  ?? null;
    $item_title   = $update['title']        ?? 'your item';

    if (!$vendor_email) {
        $vendor_row = $db->fetch("
            SELECT v.business_name AS vendor_name,
                   u.email         AS vendor_email,
                   i.title         AS item_title
            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';
        $item_title   = $vendor_row['item_title']   ?? $item_title;
    }

    // 4. Send email to vendor
    if ($vendor_email) {
        $mailer = new Mailer();
        $sent   = $mailer->sendItemUpdateApproved($vendor_email, $vendor_name, $item_title);

        if (!$sent) {
            log_message("Item-update approval email failed — update #{$update_id} to {$vendor_email}", 'warning');
        }
    }

    flash('success', 'Item update approved successfully. Vendor has been notified.', 'success');

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

redirect('updated-items.php');