<?php
/**
 * ADMIN ITEM UPDATE REVIEW PAGE
 * File: admin/item-update-review.php
 * Detailed review of item update changes
 */

require_once '../app/Core/init.php';
Auth::requireAdmin();

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

if (!$update_id) {
    flash('error', 'Invalid update ID', 'danger');
    redirect('updated-items.php');
}

$item = new Item();
$update = $item->getUpdate($update_id);

if (!$update) {
    flash('error', 'Update not found', 'danger');
    redirect('updated-items.php');
}

// Parse changes
$changes = json_decode($update['changes'], true);

// Get current item data for comparison
$current_item_sql = "SELECT * FROM items WHERE id = ?";
$current_item = $db->fetch($current_item_sql, [$update['item_id']]);

$page_title = "Review Item Update - " . APP_NAME;
$active_menu = "updated_items";

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <div class="page-header mb-4">
        <div class="header-left">
            <a href="updated-items.php" class="btn btn-secondary btn-sm mb-2">
                <i class="fas fa-arrow-left"></i> Back to Updates
            </a>
            <h1><i class="fas fa-clipboard-check"></i> Review Item Update</h1>
        </div>
    </div>

    <div class="content">
        <div class="row">
            <!-- Update Information -->
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">Update Information</h5>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($update['item_image'])): ?>
                            <img src="<?= upload('items/' . $update['item_image']) ?>" 
                                 alt="<?= esc($update['title']) ?>" 
                                 class="img-fluid rounded mb-3" 
                                 style="max-height: 150px;">
                        <?php endif; ?>
                        
                        <p><strong>Item:</strong><br><?= esc($update['title']) ?></p>
                        <p><strong>Vendor:</strong><br><?= esc($update['vendor_name']) ?> (<?= esc($update['vendor_email']) ?>)</p>
                        
                        <p><strong>Current Status:</strong><br>
                            <?= format_status_badge($update['approval_status']) ?>
                        </p>
                        
                        <p><strong>Update Submitted:</strong><br>
                            <?= !empty($update['created_at']) ? format_date($update['created_at']) : 'N/A' ?>
                            (<?= !empty($update['created_at']) ? format_time_ago($update['created_at']) : 'N/A' ?>)
                        </p>
                        
                        <?php if (!empty($update['update_reason'])): ?>
                            <p><strong>Reason for Update:</strong><br>
                                <span class="text-muted"><?= nl2br(esc($update['update_reason'])) ?></span>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Actions -->
                <?php if ($update['approval_status'] === 'pending'): ?>
                    <div class="card">
                        <div class="card-header bg-warning">
                            <h5 class="mb-0">Review Actions</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="item-update-approve.php" class="mb-2">
                                <input type="hidden" name="id" value="<?= $update_id ?>">
                                <input type="hidden" name="confirm" value="1">
                                <button type="submit" class="btn btn-success w-100" 
                                        onclick="return confirm('Are you sure you want to APPROVE these changes?')">
                                    <i class="fas fa-check-circle"></i> Accept Changes
                                </button>
                            </form>
                            
                            <form method="POST" action="item-update-reject.php">
                                <input type="hidden" name="id" value="<?= $update_id ?>">
                                <input type="hidden" name="confirm" value="1">
                                <button type="submit" class="btn btn-danger w-100"
                                        onclick="return confirm('Are you sure you want to REJECT these changes?')">
                                    <i class="fas fa-times-circle"></i> Reject Changes
                                </button>
                            </form>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="card">
                        <div class="card-header bg-secondary text-white">
                            <h5 class="mb-0">Review Status</h5>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info mb-0">
                                <strong>Status:</strong> <?= ucfirst($update['approval_status']) ?><br>
                                <strong>Reviewed by:</strong> <?= esc($update['reviewer_email'] ?? 'System') ?><br>
                                <strong>Reviewed at:</strong> <?= !empty($update['reviewed_at']) ? format_date($update['reviewed_at']) : 'N/A' ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Changes Comparison -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Changes Comparison</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($changes)): ?>
                            <p class="text-muted">No changes found</p>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th width="25%">Field</th>
                                            <th width="35%">Original Value</th>
                                            <th width="35%">New Value</th>
                                            <th width="5%">Change Type</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($changes as $field => $value): ?>
                                            <?php
                                            // Support both formats:
                                            //   New format: {field: {old: x, new: y}}  ← correct comparison
                                            //   Old format: {field: newValue}           ← fallback
                                            if (is_array($value) && array_key_exists('old', $value) && array_key_exists('new', $value)) {
                                                $original_value = $value['old'];
                                                $new_value      = $value['new'];
                                            } else {
                                                // Legacy format — old value from items table, new value from changes
                                                $original_value = $current_item[$field] ?? '';
                                                $new_value      = $value;
                                            }
                                            
                                            // Determine change type
                                            if (($original_value === null || $original_value === '') && $new_value !== null && $new_value !== '') {
                                                $change_type = '<span class="badge bg-success">Added</span>';
                                            } elseif ($original_value !== null && $original_value !== '' && ($new_value === null || $new_value === '')) {
                                                $change_type = '<span class="badge bg-danger">Removed</span>';
                                            } else {
                                                $change_type = '<span class="badge bg-info">Modified</span>';
                                            }
                                            
                                            // Format field name
                                            $field_label = ucwords(str_replace('_', ' ', $field));
                                            
                                            // Format values for display
                                            $original_display = formatFieldValue($field, $original_value);
                                            $new_display      = formatFieldValue($field, $new_value);
                                            ?>
                                            <tr>
                                                <td><strong><?= $field_label ?></strong></td>
                                                <td>
                                                    <?php if (empty($original_value)): ?>
                                                        <span class="text-muted">Empty</span>
                                                    <?php else: ?>
                                                        <?= $original_display ?>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="bg-light">
                                                    <?php if (empty($new_value)): ?>
                                                        <span class="text-muted">Empty</span>
                                                    <?php else: ?>
                                                        <strong><?= $new_display ?></strong>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-center"><?= $change_type ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Review History -->
                <?php if (!empty($update['reviewed_at'])): ?>
                    <div class="card mt-4">
                        <div class="card-header">
                            <h5 class="mb-0">Review History</h5>
                        </div>
                        <div class="card-body">
                            <p><strong>Status:</strong> <?= strtoupper($update['approval_status']) ?></p>
                            <p><strong>Reviewed by:</strong> <?= esc($update['reviewer_email'] ?? 'System') ?></p>
                            <p><strong>Reviewed at:</strong> <?= format_date($update['reviewed_at']) ?></p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/layouts/admin/footer.php'; ?>

<?php
/**
 * Helper function to format field values for display
 */
function formatFieldValue($field, $value) {
    if (is_null($value) || $value === '') {
        return '<span class="text-muted">Empty</span>';
    }
    
    switch ($field) {
        case 'price_per_day':
        case 'security_deposit':
            return '₦' . number_format($value, 2);
            
        case 'description':
        case 'features':
        case 'terms_and_conditions':
            return nl2br(esc(substr($value, 0, 200))) . (strlen($value) > 200 ? '...' : '');
            
        case 'main_image':
            return '<img src="' . upload('items/' . $value) . '" alt="Image" style="max-width: 100px; max-height: 100px;">';
            
        case 'status':
        case 'approval_status':
        case 'condition_status':
            return '<span class="badge bg-secondary">' . ucfirst($value) . '</span>';
            
        default:
            return esc($value);
    }
}
?>