<?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;
            
        // Admin User Management
        case 'add_admin_user':
            addAdminUser($db);
            break;
            
        case 'update_admin_user':
            updateAdminUser($db);
            break;
            
        case 'toggle_admin_status':
            toggleAdminStatus($db);
            break;
            
        case 'get_admin_details':
            getAdminDetails($db);
            break;
            
        case 'get_admin_permissions':
            getAdminPermissions($db);
            break;
            
        case 'get_user_details':
            getUserDetails($db);
            break;
            
        case 'update_user':
            updateUser($db);
            break;
            
        case 'export_users':
            exportUsers($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');
    }
}

/**
 * Add new admin user
 */
function addAdminUser($db) {
    $required = ['full_name', 'phone_number', 'password', 'admin_role_id'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
        }
    }
    
    try {
        $db->beginTransaction();
        
        $phone = validatePhone($_POST['phone_number']);
        if (!$phone) {
            jsonError('Invalid phone number format');
        }
        
        // Check if phone exists
        $sql = "SELECT id FROM users WHERE phone_number = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$phone]);
        if ($stmt->fetch()) {
            jsonError('Phone number already registered');
        }
        
        $passwordHash = hashPassword($_POST['password']);
        
        $sql = "INSERT INTO users 
                (phone_number, password_hash, full_name, email, user_type, admin_role_id, 
                 region_id, district_id, is_verified, approval_status) 
                VALUES (?, ?, ?, ?, 'admin', ?, ?, ?, 1, 'approved')";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $phone,
            $passwordHash,
            sanitize($_POST['full_name']),
            sanitize($_POST['email'] ?? ''),
            (int)$_POST['admin_role_id'],
            !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
            !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null
        ]);
        
        $userId = $db->lastInsertId();
        
        // Log activity
        $sql = "INSERT INTO admin_activity_log (admin_id, action_type, action_description, affected_table, affected_record_id) 
                VALUES (?, 'create', 'Created new admin user', 'users', ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([getUserId(), $userId]);
        
        $db->commit();
        
        jsonSuccess('Admin user created successfully');
        
    } catch (PDOException $e) {
        $db->rollBack();
        logError('Add Admin User Error: ' . $e->getMessage());
        jsonError('Failed to create admin user: ' . $e->getMessage());
    }
}

/**
 * Update admin user
 */
function updateAdminUser($db) {
    $adminId = $_POST['admin_id'] ?? null;
    
    if (!$adminId) {
        jsonError('Admin ID is required');
    }
    
    try {
        $sql = "UPDATE users 
                SET full_name = ?, 
                    email = ?, 
                    admin_role_id = ?,
                    updated_at = NOW() 
                WHERE id = ? AND user_type IN ('admin', 'super_admin')";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            sanitize($_POST['full_name']),
            sanitize($_POST['email'] ?? ''),
            (int)$_POST['admin_role_id'],
            $adminId
        ]);
        
        // Log activity
        $sql = "INSERT INTO admin_activity_log (admin_id, action_type, action_description, affected_table, affected_record_id) 
                VALUES (?, 'update', 'Updated admin user details', 'users', ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([getUserId(), $adminId]);
        
        jsonSuccess('Admin user updated successfully');
        
    } catch (PDOException $e) {
        logError('Update Admin User Error: ' . $e->getMessage());
        jsonError('Failed to update admin user');
    }
}

/**
 * Toggle admin status
 */
function toggleAdminStatus($db) {
    $adminId = $_POST['admin_id'] ?? null;
    $isActive = $_POST['is_active'] ?? 1;
    
    if (!$adminId) {
        jsonError('Admin ID is required');
    }
    
    if ($adminId == getUserId()) {
        jsonError('You cannot deactivate your own account');
    }
    
    try {
        $sql = "UPDATE users SET is_active = ?, updated_at = NOW() 
                WHERE id = ? AND user_type IN ('admin', 'super_admin')";
        $stmt = $db->prepare($sql);
        $stmt->execute([$isActive, $adminId]);
        
        $action = $isActive ? 'activated' : 'deactivated';
        
        // Log activity
        $sql = "INSERT INTO admin_activity_log (admin_id, action_type, action_description, affected_table, affected_record_id) 
                VALUES (?, 'update', ?, 'users', ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([getUserId(), "Admin user $action", $adminId]);
        
        jsonSuccess("Admin user $action successfully");
        
    } catch (PDOException $e) {
        logError('Toggle Admin Status Error: ' . $e->getMessage());
        jsonError('Failed to update status');
    }
}

/**
 * Get admin details
 */
function getAdminDetails($db) {
    $adminId = $_GET['admin_id'] ?? null;
    
    if (!$adminId) {
        jsonError('Admin ID is required');
    }
    
    try {
        $sql = "SELECT 
                    u.id, u.full_name, u.phone_number, u.email, u.admin_role_id,
                    ar.role_name, ar.role_level
                FROM users u
                LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
                WHERE u.id = ? AND u.user_type IN ('admin', 'super_admin')";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$adminId]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$admin) {
            jsonError('Admin not found', 404);
        }
        
        jsonSuccess('Admin details retrieved', $admin);
        
    } catch (PDOException $e) {
        logError('Get Admin Details Error: ' . $e->getMessage());
        jsonError('Failed to fetch admin details');
    }
}

/**
 * Get admin permissions
 */
function getAdminPermissions($db) {
    $adminId = $_GET['admin_id'] ?? null;
    
    if (!$adminId) {
        jsonError('Admin ID is required');
    }
    
    try {
        $sql = "SELECT 
                    p.permission_key,
                    p.permission_name,
                    p.permission_description,
                    p.permission_category
                FROM admin_permissions p
                JOIN role_permissions rp ON p.id = rp.permission_id
                JOIN admin_roles ar ON rp.role_id = ar.id
                JOIN users u ON u.admin_role_id = ar.id
                WHERE u.id = ? AND ar.is_active = 1
                ORDER BY p.permission_category, p.permission_name";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$adminId]);
        $permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Permissions retrieved', $permissions);
        
    } catch (PDOException $e) {
        logError('Get Admin Permissions Error: ' . $e->getMessage());
        jsonError('Failed to fetch permissions');
    }
}

/**
 * Get user details
 */
function getUserDetails($db) {
    $userId = $_GET['user_id'] ?? null;
    
    if (!$userId) {
        jsonError('User ID is required');
    }
    
    try {
        $sql = "SELECT 
                    u.id, u.full_name, u.phone_number, u.email, u.user_type,
                    u.is_active, u.is_verified, u.approval_status,
                    u.created_at, u.last_login, u.last_activity,
                    r.region_name, d.district_name, s.subcounty_name, 
                    p.parish_name, v.village_name,
                    ar.role_name
                FROM users u
                LEFT JOIN regions r ON u.region_id = r.id
                LEFT JOIN districts d ON u.district_id = d.id
                LEFT JOIN subcounties s ON u.subcounty_id = s.id
                LEFT JOIN parishes p ON u.parish_id = p.id
                LEFT JOIN villages v ON u.village_id = v.id
                LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
                WHERE u.id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            jsonError('User not found', 404);
        }
        
        // Build location string
        $location = [];
        if ($user['village_name']) $location[] = $user['village_name'];
        if ($user['parish_name']) $location[] = $user['parish_name'];
        if ($user['subcounty_name']) $location[] = $user['subcounty_name'];
        if ($user['district_name']) $location[] = $user['district_name'];
        if ($user['region_name']) $location[] = $user['region_name'];
        
        $user['location'] = !empty($location) ? implode(', ', $location) : 'Not set';
        
        jsonSuccess('User details retrieved', $user);
        
    } catch (PDOException $e) {
        logError('Get User Details Error: ' . $e->getMessage());
        jsonError('Failed to fetch user details');
    }
}

/**
 * Update user
 */
function updateUser($db) {
    $userId = $_POST['user_id'] ?? null;
    $fullName = sanitize($_POST['full_name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    
    if (!$userId || !$fullName) {
        jsonError('User ID and full name are required');
    }
    
    try {
        $sql = "UPDATE users 
                SET full_name = ?, 
                    email = ?,
                    updated_at = NOW() 
                WHERE id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$fullName, $email, $userId]);
        
        if ($stmt->rowCount() > 0) {
            // Log activity
            $logSql = "INSERT INTO admin_activity_log (admin_id, action_type, action_description, affected_table, affected_record_id) 
                       VALUES (?, 'update', 'Updated user profile', 'users', ?)";
            $logStmt = $db->prepare($logSql);
            $logStmt->execute([getUserId(), $userId]);
            
            jsonSuccess('User updated successfully');
        } else {
            jsonError('No changes made or user not found');
        }
        
    } catch (PDOException $e) {
        logError('Update User Error: ' . $e->getMessage());
        jsonError('Failed to update user');
    }
}

/**
 * Export users to CSV
 */
function exportUsers($db) {
    try {
        $sql = "SELECT 
                    u.id,
                    u.full_name,
                    u.phone_number,
                    u.email,
                    u.user_type,
                    CASE WHEN u.is_active = 1 THEN 'Active' ELSE 'Inactive' END as status,
                    CASE WHEN u.is_verified = 1 THEN 'Yes' ELSE 'No' END as verified,
                    d.district_name as district,
                    s.subcounty_name as subcounty,
                    u.created_at,
                    u.last_login
                FROM users u
                LEFT JOIN districts d ON u.district_id = d.id
                LEFT JOIN subcounties s ON u.subcounty_id = s.id
                ORDER BY u.created_at DESC";
        
        $stmt = $db->query($sql);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Set headers for CSV download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="users_' . date('Y-m-d') . '.csv"');
        
        $output = fopen('php://output', 'w');
        
        // Add CSV headers
        fputcsv($output, ['ID', 'Full Name', 'Phone', 'Email', 'Type', 'Status', 'Verified', 'District', 'Subcounty', 'Registered', 'Last Login']);
        
        // Add data rows
        foreach ($users as $user) {
            fputcsv($output, [
                $user['id'],
                $user['full_name'],
                $user['phone_number'],
                $user['email'] ?? '',
                ucwords(str_replace('_', ' ', $user['user_type'])),
                $user['status'],
                $user['verified'],
                $user['district'] ?? '',
                $user['subcounty'] ?? '',
                $user['created_at'],
                $user['last_login'] ?? ''
            ]);
        }
        
        fclose($output);
        exit;
        
    } catch (PDOException $e) {
        logError('Export Users Error: ' . $e->getMessage());
        jsonError('Failed to export users');
    }
}
?>