<?php
/**
 * ============================================================================
 * api/admin.php - Admin API Handler
 * Handles approval, CRUD operations, and administrative tasks
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Check if user is admin
if (!isLoggedIn() || getUserType() !== 'admin') {
    jsonError('Unauthorized access', 403);
}

$database = new Database();
$db = $database->getConnection();

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'approve_user':
            approveUser($db);
            break;
            
        case 'reject_user':
            rejectUser($db);
            break;
            
        case 'add_location':
            addLocation($db);
            break;
            
        case 'edit_location':
            editLocation($db);
            break;
            
        case 'delete_location':
            deleteLocation($db);
            break;
            
        case 'add_market_price':
            addMarketPrice($db);
            break;
            
        case 'edit_market_price':
            editMarketPrice($db);
            break;
            
        case 'delete_market_price':
            deleteMarketPrice($db);
            break;
            
        case 'add_tip':
            addAgricultureTip($db);
            break;
            
        case 'edit_tip':
            editAgricultureTip($db);
            break;
            
        case 'delete_tip':
            deleteAgricultureTip($db);
            break;
            
        case 'resolve_report':
            resolveReport($db);
            break;
            
        case 'update_user_status':
            updateUserStatus($db);
            break;
            
        default:
            jsonError('Invalid action', 400);
    }
} catch (Exception $e) {
    logError('Admin API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage(), 500);
}

/**
 * Approve user registration
 */
function approveUser($db) {
    $approvalId = $_POST['approval_id'] ?? null;
    
    if (!$approvalId) {
        jsonError('Approval ID is required');
    }
    
    try {
        $db->beginTransaction();
        
        // Get approval details
        $sql = "SELECT * FROM user_approvals WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$approvalId]);
        $approval = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$approval) {
            jsonError('Approval not found');
        }
        
        // Update approval status
        $sql = "UPDATE user_approvals 
                SET approval_status = 'approved', 
                    approved_by = ?, 
                    approved_at = NOW() 
                WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([getUserId(), $approvalId]);
        
        $db->commit();
        
        jsonSuccess('User approved successfully');
        
    } catch (PDOException $e) {
        $db->rollBack();
        logError('Approve User Error: ' . $e->getMessage());
        jsonError('Failed to approve user');
    }
}

/**
 * Reject user registration
 */
function rejectUser($db) {
    $approvalId = $_POST['approval_id'] ?? null;
    $reason = $_POST['reason'] ?? '';
    
    if (!$approvalId) {
        jsonError('Approval ID is required');
    }
    
    try {
        $db->beginTransaction();
        
        // Update approval status
        $sql = "UPDATE user_approvals 
                SET approval_status = 'rejected', 
                    rejection_reason = ?,
                    approved_by = ?, 
                    approved_at = NOW() 
                WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$reason, getUserId(), $approvalId]);
        
        $db->commit();
        
        jsonSuccess('User rejected');
        
    } catch (PDOException $e) {
        $db->rollBack();
        logError('Reject User Error: ' . $e->getMessage());
        jsonError('Failed to reject user');
    }
}

/**
 * Add new location
 */
function addLocation($db) {
    $type = $_POST['type'] ?? '';
    $name = sanitize($_POST['name'] ?? '');
    $code = sanitize($_POST['code'] ?? '');
    $parentId = $_POST['parent_id'] ?? null;
    
    if (!$type || !$name) {
        jsonError('Type and name are required');
    }
    
    try {
        $table = $type;
        $nameField = rtrim($type, 's') . '_name';
        $codeField = rtrim($type, 's') . '_code';
        
        if ($type === 'regions') {
            $sql = "INSERT INTO $table ($nameField, $codeField) VALUES (?, ?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$name, $code]);
        } else {
            $parentField = [
                'districts' => 'region_id',
                'subcounties' => 'district_id',
                'parishes' => 'subcounty_id',
                'villages' => 'parish_id'
            ][$type];
            
            $sql = "INSERT INTO $table ($parentField, $nameField, $codeField) VALUES (?, ?, ?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$parentId, $name, $code]);
        }
        
        jsonSuccess('Location added successfully');
        
    } catch (PDOException $e) {
        logError('Add Location Error: ' . $e->getMessage());
        jsonError('Failed to add location');
    }
}

/**
 * Edit existing location
 */
function editLocation($db) {
    $id = $_POST['id'] ?? null;
    $type = $_POST['type'] ?? '';
    $name = sanitize($_POST['name'] ?? '');
    $code = sanitize($_POST['code'] ?? '');
    
    if (!$id || !$type || !$name) {
        jsonError('ID, type, and name are required');
    }
    
    try {
        $table = $type;
        $nameField = rtrim($type, 's') . '_name';
        $codeField = rtrim($type, 's') . '_code';
        
        $sql = "UPDATE $table SET $nameField = ?, $codeField = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$name, $code, $id]);
        
        if ($stmt->rowCount() > 0) {
            jsonSuccess('Location updated successfully');
        } else {
            jsonError('Location not found or no changes made');
        }
        
    } catch (PDOException $e) {
        logError('Edit Location Error: ' . $e->getMessage());
        jsonError('Failed to update location');
    }
}

/**
 * Delete location
 */
function deleteLocation($db) {
    $id = $_POST['id'] ?? null;
    $type = $_POST['type'] ?? '';
    
    if (!$id || !$type) {
        jsonError('ID and type are required');
    }
    
    try {
        $sql = "DELETE FROM $type WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$id]);
        
        jsonSuccess('Location deleted successfully');
        
    } catch (PDOException $e) {
        logError('Delete Location Error: ' . $e->getMessage());
        jsonError('Failed to delete location. It may have child locations.');
    }
}

/**
 * Add market price
 */
function addMarketPrice($db) {
    $productType = sanitize($_POST['product_type'] ?? '');
    $marketLocation = sanitize($_POST['market_location'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $unit = sanitize($_POST['unit'] ?? '');
    $source = sanitize($_POST['source'] ?? 'Manual Entry');
    $priceDate = $_POST['price_date'] ?? date('Y-m-d');
    
    if (!$productType || !$marketLocation || !$price || !$unit) {
        jsonError('All fields are required');
    }
    
    try {
        $sql = "INSERT INTO market_prices (product_type, market_location, price, unit, source, price_date) 
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$productType, $marketLocation, $price, $unit, $source, $priceDate]);
        
        jsonSuccess('Market price added successfully');
        
    } catch (PDOException $e) {
        logError('Add Market Price Error: ' . $e->getMessage());
        jsonError('Failed to add market price');
    }
}

/**
 * Edit market price
 */
function editMarketPrice($db) {
    $id = $_POST['id'] ?? null;
    $price = floatval($_POST['price'] ?? 0);
    $source = sanitize($_POST['source'] ?? '');
    
    if (!$id || !$price) {
        jsonError('ID and price are required');
    }
    
    try {
        $sql = "UPDATE market_prices SET price = ?, source = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$price, $source, $id]);
        
        jsonSuccess('Market price updated successfully');
        
    } catch (PDOException $e) {
        logError('Edit Market Price Error: ' . $e->getMessage());
        jsonError('Failed to update market price');
    }
}

/**
 * Delete market price
 */
function deleteMarketPrice($db) {
    $id = $_POST['id'] ?? null;
    
    if (!$id) {
        jsonError('ID is required');
    }
    
    try {
        $sql = "DELETE FROM market_prices WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$id]);
        
        jsonSuccess('Market price deleted successfully');
        
    } catch (PDOException $e) {
        logError('Delete Market Price Error: ' . $e->getMessage());
        jsonError('Failed to delete market price');
    }
}

/**
 * Add agricultural tip
 */
function addAgricultureTip($db) {
    $title = sanitize($_POST['title'] ?? '');
    $content = sanitize($_POST['content'] ?? '');
    $category = $_POST['category'] ?? '';
    $cropType = sanitize($_POST['crop_type'] ?? '');
    $language = $_POST['language'] ?? 'en';
    
    if (!$title || !$content || !$category) {
        jsonError('Title, content, and category are required');
    }
    
    try {
        $sql = "INSERT INTO agricultural_tips (title, content, category, crop_type, language, created_by) 
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$title, $content, $category, $cropType, $language, getUserId()]);
        
        jsonSuccess('Agricultural tip added successfully');
        
    } catch (PDOException $e) {
        logError('Add Tip Error: ' . $e->getMessage());
        jsonError('Failed to add tip');
    }
}

/**
 * Edit agricultural tip
 */
function editAgricultureTip($db) {
    $id = $_POST['id'] ?? null;
    $title = sanitize($_POST['title'] ?? '');
    $content = sanitize($_POST['content'] ?? '');
    $category = $_POST['category'] ?? '';
    
    if (!$id || !$title || !$content) {
        jsonError('Required fields missing');
    }
    
    try {
        $sql = "UPDATE agricultural_tips 
                SET title = ?, content = ?, category = ?, updated_at = NOW() 
                WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$title, $content, $category, $id]);
        
        jsonSuccess('Agricultural tip updated successfully');
        
    } catch (PDOException $e) {
        logError('Edit Tip Error: ' . $e->getMessage());
        jsonError('Failed to update tip');
    }
}

/**
 * Delete agricultural tip
 */
function deleteAgricultureTip($db) {
    $id = $_POST['id'] ?? null;
    
    if (!$id) {
        jsonError('ID is required');
    }
    
    try {
        $sql = "DELETE FROM agricultural_tips WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$id]);
        
        jsonSuccess('Agricultural tip deleted successfully');
        
    } catch (PDOException $e) {
        logError('Delete Tip Error: ' . $e->getMessage());
        jsonError('Failed to delete tip');
    }
}

/**
 * Resolve report
 */
function resolveReport($db) {
    $id = $_POST['id'] ?? null;
    $status = $_POST['status'] ?? 'resolved';
    $adminNotes = sanitize($_POST['admin_notes'] ?? '');
    
    if (!$id) {
        jsonError('Report ID is required');
    }
    
    try {
        $sql = "UPDATE reports 
                SET status = ?, admin_notes = ?, resolved_at = NOW() 
                WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$status, $adminNotes, $id]);
        
        jsonSuccess('Report updated successfully');
        
    } catch (PDOException $e) {
        logError('Resolve Report Error: ' . $e->getMessage());
        jsonError('Failed to update report');
    }
}

/**
 * Update user status
 */
function updateUserStatus($db) {
    $userId = $_POST['user_id'] ?? null;
    $isActive = $_POST['is_active'] ?? 1;
    
    if (!$userId) {
        jsonError('User ID is required');
    }
    
    try {
        $sql = "UPDATE users SET is_active = ? WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$isActive, $userId]);
        
        $action = $isActive ? 'activated' : 'deactivated';
        jsonSuccess("User $action successfully");
        
    } catch (PDOException $e) {
        logError('Update User Status Error: ' . $e->getMessage());
        jsonError('Failed to update user status');
    }
}
?>