<?php
/**
 * APPROVE ITEM API
 * File: api/approve-item.php
 * Approve or reject item listing (Admin only)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

// Require admin authentication
Auth::requireLogin();
Auth::requireRole('admin');

$admin_id = Auth::id();

// Only allow POST/PUT/PATCH requests
if (!in_array($_SERVER['REQUEST_METHOD'], ['POST', 'PUT', 'PATCH'])) {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        $input = $_POST;
    }
    
    // Validate required fields
    $required_fields = ['item_id', 'action'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode(['error' => "Field '$field' is required"]);
            exit;
        }
    }
    
    $item_id = (int)$input['item_id'];
    $action = strtolower($input['action']); // approve or reject
    $admin_notes = $input['admin_notes'] ?? null;
    $reason = $input['reason'] ?? null;
    $additional_data = $input['data'] ?? [];
    
    if (!in_array($action, ['approve', 'reject'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Action must be either "approve" or "reject"']);
        exit;
    }
    
    $item = new Item();
    $item_data = $item->find($item_id);
    
    if (!$item_data) {
        http_response_code(404);
        echo json_encode(['error' => 'Item not found']);
        exit;
    }
    
    // Check if item is in pending status
    if ($item_data['approval_status'] !== 'pending') {
        http_response_code(400);
        echo json_encode(['error' => 'Item is not in pending status and cannot be modified']);
        exit;
    }
    
    $db = Database::getInstance();
    $old_status = $item_data['approval_status'];
    $new_status = null;
    $response = ['success' => true, 'message' => ''];
    
    // Get vendor information for notifications
    $vendor_sql = "SELECT v.id as vendor_id, u.email as vendor_email, u.first_name, u.last_name
                  FROM vendors v
                  JOIN users u ON v.user_id = u.id
                  WHERE v.id = ?";
    $vendor_info = $db->fetch($vendor_sql, [$item_data['vendor_id']]);
    
    switch ($action) {
        case 'approve':
            $new_status = 'approved';
            $response['message'] = 'Item approved successfully';
            
            // Validate item data before approval
            $validation_errors = [];
            
            // Check required fields
            if (empty($item_data['title'])) {
                $validation_errors[] = 'Item title is required';
            }
            
            if (empty($item_data['description'])) {
                $validation_errors[] = 'Item description is required';
            }
            
            if (empty($item_data['main_image'])) {
                $validation_errors[] = 'Main image is required';
            }
            
            if (empty($item_data['price_per_day']) || $item_data['price_per_day'] <= 0) {
                $validation_errors[] = 'Valid daily price is required';
            }
            
            if (empty($item_data['category_id'])) {
                $validation_errors[] = 'Category is required';
            }
            
            if (empty($item_data['city']) || empty($item_data['state'])) {
                $validation_errors[] = 'Location (city and state) is required';
            }
            
            // Check for inappropriate content
            $inappropriate_words = ['spam', 'scam', 'fake', 'fraud', 'illegal'];
            $content_to_check = strtolower($item_data['title'] . ' ' . $item_data['description']);
            
            foreach ($inappropriate_words as $word) {
                if (strpos($content_to_check, $word) !== false) {
                    $validation_errors[] = "Item content contains inappropriate language: '$word'";
                    break;
                }
            }
            
            // Check image quality (if implemented)
            // This would involve analyzing the uploaded image
            
            if (!empty($validation_errors)) {
                throw new Exception('Item validation failed: ' . implode(', ', $validation_errors));
            }
            
            // Set default values if not provided
            $updates = [
                'approval_status' => 'approved',
                'approved_at' => 'NOW()',
                'approved_by' => $admin_id,
                'admin_notes' => $admin_notes,
                'is_active' => 1
            ];
            
            // Check if vendor is verified (optional requirement)
            if ($vendor_info && $additional_data['require_verified_vendor'] ?? false) {
                $vendor_status_sql = "SELECT status FROM vendors WHERE id = ?";
                $vendor_status = $db->fetch($vendor_status_sql, [$vendor_info['vendor_id']]);
                
                if ($vendor_status['status'] !== 'approved') {
                    throw new Exception('Vendor must be verified before item approval');
                }
            }
            
            break;
            
        case 'reject':
            $new_status = 'rejected';
            $response['message'] = 'Item rejected successfully';
            
            if (empty($reason) && empty($admin_notes)) {
                throw new Exception('Rejection reason is required when rejecting an item');
            }
            
            $updates = [
                'approval_status' => 'rejected',
                'rejected_at' => 'NOW()',
                'rejected_by' => $admin_id,
                'rejection_reason' => $reason,
                'admin_notes' => $admin_notes,
                'is_active' => 0
            ];
            
            break;
    }
    
    // Build dynamic UPDATE query
    $update_fields = [];
    $params = [];
    
    foreach ($updates as $field => $value) {
        if ($value === 'NOW()') {
            $update_fields[] = "$field = NOW()";
        } else {
            $update_fields[] = "$field = ?";
            $params[] = $value;
        }
    }
    
    $params[] = $item_id; // For WHERE clause
    $update_sql = "UPDATE items SET " . implode(', ', $update_fields) . " WHERE id = ?";
    $db->execute($update_sql, $params);
    
    // Update timestamp
    $db->execute("UPDATE items SET updated_at = NOW() WHERE id = ?", [$item_id]);
    
    // Log the approval/rejection
    $log_sql = "INSERT INTO item_approval_history (item_id, admin_id, action, old_status, new_status, reason, notes, created_at) 
               VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
    $db->execute($log_sql, [
        $item_id,
        $admin_id,
        $action,
        $old_status,
        $new_status,
        $reason,
        $admin_notes
    ]);
    
    $response['old_status'] = $old_status;
    $response['new_status'] = $new_status;
    $response['item_title'] = $item_data['title'];
    $response['vendor_id'] = $item_data['vendor_id'];
    
    // Send notification to vendor
    if ($vendor_info) {
        $notification_service = new NotificationService();
        
        if ($action === 'approve') {
            $notification_data = [
                'item_title' => $item_data['title'],
                'approval_date' => date('Y-m-d H:i:s')
            ];
            
            $notification_service->send(
                $vendor_info['vendor_email'],
                'Item Approved - Ready to Rent!',
                'item_approved',
                $notification_data
            );
            
            $response['notified_vendor'] = true;
        } else {
            $notification_data = [
                'item_title' => $item_data['title'],
                'rejection_reason' => $reason,
                'admin_notes' => $admin_notes
            ];
            
            $notification_service->send(
                $vendor_info['vendor_email'],
                'Item Rejected - Action Required',
                'item_rejected',
                $notification_data
            );
            
            $response['notified_vendor'] = true;
        }
    }
    
    // Update vendor statistics if item is approved
    if ($action === 'approve') {
        $vendor_stats_sql = "UPDATE vendors SET 
                            total_items = total_items + 1,
                            approved_items = approved_items + 1,
                            updated_at = NOW()
                            WHERE id = ?";
        $db->execute($vendor_stats_sql, [$item_data['vendor_id']]);
        
        $response['vendor_stats_updated'] = true;
    }
    
    // Send analytics data (if tracking approval metrics)
    $analytics_data = [
        'action' => $action,
        'item_id' => $item_id,
        'admin_id' => $admin_id,
        'vendor_id' => $item_data['vendor_id'],
        'category_id' => $item_data['category_id'],
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    // Log the action
    log_info("Item $action", [
        'item_id' => $item_id,
        'admin_id' => $admin_id,
        'vendor_id' => $item_data['vendor_id'],
        'action' => $action,
        'old_status' => $old_status,
        'new_status' => $new_status,
        'reason' => $reason,
        'ip' => get_client_ip()
    ]);
    
    // Additional actions based on approval
    if ($action === 'approve') {
        // Auto-feature premium items (if criteria met)
        if ($additional_data['auto_feature'] ?? false) {
            $premium_criteria = [
                'has_multiple_images' => !empty($item_data['additional_images']),
                'has_detailed_description' => strlen($item_data['description']) > 100,
                'has_tags' => !empty($item_data['tags']),
                'reasonable_price' => $item_data['price_per_day'] > 100 && $item_data['price_per_day'] < 10000
            ];
            
            $criteria_met = array_sum($premium_criteria) >= 3;
            
            if ($criteria_met) {
                $feature_sql = "UPDATE items SET is_featured = 1, featured_until = DATE_ADD(NOW(), INTERVAL 30 DAY) WHERE id = ?";
                $db->execute($feature_sql, [$item_id]);
                
                $response['auto_featured'] = true;
                $response['feature_expires'] = date('Y-m-d H:i:s', strtotime('+30 days'));
            }
        }
        
        // Check for duplicate items (basic check)
        $duplicate_sql = "SELECT COUNT(*) as count 
                         FROM items 
                         WHERE title = ? 
                         AND vendor_id = ? 
                         AND id != ? 
                         AND approval_status = 'approved'";
        $duplicates = $db->fetch($duplicate_sql, [$item_data['title'], $item_data['vendor_id'], $item_id]);
        
        if ($duplicates['count'] > 0) {
            $response['warning'] = 'Similar item title detected - monitor for duplicates';
            $response['duplicate_count'] = $duplicates['count'];
        }
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    log_error('Item approval error', $e->getMessage(), [
        'item_id' => $input['item_id'] ?? null,
        'action' => $input['action'] ?? null,
        'admin_id' => $admin_id,
        'input' => $input,
        'trace' => $e->getTraceAsString()
    ]);
    
    http_response_code(400);
    echo json_encode([
        'error' => $e->getMessage(),
        'code' => 'APPROVAL_ERROR'
    ]);
}