-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 18, 2026 at 07:53 AM
-- Server version: 10.4.32-MariaDB-log
-- PHP Version: 8.2.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `aims_db`
--

DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `add_chat_member` (IN `p_chat_id` INT, IN `p_user_id` INT, IN `p_role` VARCHAR(20))   BEGIN
    DECLARE v_chat_type VARCHAR(20);
    DECLARE v_member_count INT;
    
    -- Get chat type
    SELECT chat_type INTO v_chat_type
    FROM chats
    WHERE id = p_chat_id;
    
    -- Count existing members
    SELECT COUNT(*) INTO v_member_count
    FROM chat_members
    WHERE chat_id = p_chat_id;
    
    -- Check if adding this member is allowed
    IF v_chat_type = 'one_to_one' AND v_member_count >= 2 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Cannot add more than 2 members to one-to-one chat';
    ELSE
        INSERT INTO chat_members (chat_id, user_id, role, joined_at)
        VALUES (p_chat_id, p_user_id, p_role, NOW());
    END IF;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `add_permission_with_auto_assign` (IN `perm_key` VARCHAR(50), IN `perm_name` VARCHAR(100), IN `perm_desc` TEXT, IN `perm_category` ENUM('users','content','system','data','reports'), IN `auto_assign_to_admin` BOOLEAN)   BEGIN
    DECLARE new_perm_id INT;
    DECLARE super_admin_role_id INT;
    DECLARE admin_role_id INT;
    
    -- Insert the new permission
    INSERT INTO admin_permissions (permission_key, permission_name, permission_description, permission_category)
    VALUES (perm_key, perm_name, perm_desc, perm_category);
    
    SET new_perm_id = LAST_INSERT_ID();
    
    -- Get role IDs
    SELECT id INTO super_admin_role_id FROM admin_roles WHERE role_level >= 10 AND is_active = 1 LIMIT 1;
    SELECT id INTO admin_role_id FROM admin_roles WHERE role_level = 8 AND is_active = 1 LIMIT 1;
    
    -- Always assign to Super Admin
    IF super_admin_role_id IS NOT NULL THEN
        INSERT INTO role_permissions (role_id, permission_id, granted_at, granted_by)
        VALUES (super_admin_role_id, new_perm_id, NOW(), @current_admin_id);
    END IF;
    
    -- Optionally assign to Administrator
    IF auto_assign_to_admin AND admin_role_id IS NOT NULL THEN
        INSERT INTO role_permissions (role_id, permission_id, granted_at, granted_by)
        VALUES (admin_role_id, new_perm_id, NOW(), @current_admin_id);
    END IF;
    
    SELECT CONCAT('Permission "', perm_name, '" created with ID ', new_perm_id) AS result;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `AwardAchievements` (IN `p_user_id` INT)   BEGIN
    -- Top Seller (50+ products sold)
    IF (SELECT COUNT(*) FROM orders WHERE seller_id = p_user_id AND status = 'completed') >= 50 THEN
        INSERT IGNORE INTO user_achievements (user_id, achievement_type, achievement_name, achievement_description, icon_url)
        VALUES (p_user_id, 'top_seller', 'Top Seller', 'Sold 50+ products successfully', '/assets/images/badges/top-seller.png');
    END IF;
    
    -- Five Star Rated
    IF (SELECT AVG(rating) FROM reviews WHERE reviewed_user_id = p_user_id) >= 4.5 
       AND (SELECT COUNT(*) FROM reviews WHERE reviewed_user_id = p_user_id) >= 10 THEN
        INSERT IGNORE INTO user_achievements (user_id, achievement_type, achievement_name, achievement_description, icon_url)
        VALUES (p_user_id, 'five_star_rated', 'Five Star Member', 'Maintained 4.5+ rating with 10+ reviews', '/assets/images/badges/five-star.png');
    END IF;
    
    -- Community Leader (20+ friends)
    IF (SELECT COUNT(*) FROM friendships 
        WHERE (user_id = p_user_id OR friend_id = p_user_id) 
        AND status = 'accepted') >= 20 THEN
        INSERT IGNORE INTO user_achievements (user_id, achievement_type, achievement_name, achievement_description, icon_url)
        VALUES (p_user_id, 'community_leader', 'Community Leader', 'Connected with 20+ farmers', '/assets/images/badges/community-leader.png');
    END IF;
    
    -- Knowledge Sharer (10+ helpful posts)
    IF (SELECT COUNT(*) FROM posts WHERE user_id = p_user_id AND likes_count >= 5) >= 10 THEN
        INSERT IGNORE INTO user_achievements (user_id, achievement_type, achievement_name, achievement_description, icon_url)
        VALUES (p_user_id, 'knowledge_sharer', 'Knowledge Sharer', 'Shared valuable farming knowledge', '/assets/images/badges/knowledge-sharer.png');
    END IF;
    
    -- Active Contributor
    IF (SELECT DATEDIFF(NOW(), created_at) FROM users WHERE id = p_user_id) >= 365
       AND (SELECT last_login FROM users WHERE id = p_user_id) >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN
        INSERT IGNORE INTO user_achievements (user_id, achievement_type, achievement_name, achievement_description, icon_url)
        VALUES (p_user_id, 'active_contributor', 'Active Contributor', 'Active for over a year', '/assets/images/badges/active-contributor.png');
    END IF;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `calculate_seasonal_patterns` ()   BEGIN
    TRUNCATE TABLE seasonal_price_patterns;
    
    INSERT INTO seasonal_price_patterns (product_type, month, avg_price_index, typical_low_price, typical_high_price, volatility_score, data_points)
    SELECT 
        product_type,
        MONTH(price_date) as month,
        AVG(price) / (SELECT AVG(price) FROM market_prices mp2 WHERE mp2.product_type = mp.product_type) as avg_price_index,
        MIN(price) as typical_low_price,
        MAX(price) as typical_high_price,
        STDDEV(price) / AVG(price) as volatility_score,
        COUNT(*) as data_points
    FROM market_prices mp
    WHERE price_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR)
    GROUP BY product_type, MONTH(price_date);
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `check_price_alerts` ()   BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE v_alert_id INT;
    DECLARE v_user_id INT;
    DECLARE v_product_type VARCHAR(50);
    DECLARE v_target_price DECIMAL(10,2);
    DECLARE v_condition VARCHAR(10);
    DECLARE v_current_price DECIMAL(10,2);
    
    DECLARE alert_cursor CURSOR FOR 
        SELECT id, user_id, product_type, target_price, alert_condition
        FROM price_alerts 
        WHERE is_active = 1;
    
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
    OPEN alert_cursor;
    
    read_loop: LOOP
        FETCH alert_cursor INTO v_alert_id, v_user_id, v_product_type, v_target_price, v_condition;
        
        IF done THEN
            LEAVE read_loop;
        END IF;
        
        -- Get current average price
        SELECT AVG(price) INTO v_current_price
        FROM market_prices
        WHERE product_type = v_product_type
        AND price_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);
        
        -- Check if alert should be triggered
        IF (v_condition = 'above' AND v_current_price >= v_target_price) OR
           (v_condition = 'below' AND v_current_price <= v_target_price) THEN
            
            -- Insert notification
            INSERT INTO notifications (user_id, title, message, type, icon, link)
            VALUES (
                v_user_id,
                'Price Alert Triggered',
                CONCAT(v_product_type, ' price is now ', FORMAT(v_current_price, 2)),
                'info',
                'tag',
                '/prices/'
            );
            
            -- Update last triggered
            UPDATE price_alerts 
            SET last_triggered = NOW() 
            WHERE id = v_alert_id;
        END IF;
    END LOOP;
    
    CLOSE alert_cursor;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `CleanExpiredSessionKeys` ()   BEGIN
    DELETE FROM session_keys WHERE expires_at < NOW();
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `cleanup_old_sessions` (IN `p_days_old` INT)   BEGIN
    DECLARE deleted_count INT;
    
    -- Delete old session context
    DELETE FROM ai_session_context
    WHERE updated_at < DATE_SUB(CURDATE(), INTERVAL p_days_old DAY);
    
    SET deleted_count = ROW_COUNT();
    
    SELECT CONCAT('Deleted ', deleted_count, ' session context records older than ', p_days_old, ' days') as result;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetAdminDashboardStats` ()   BEGIN
    SELECT 
        (SELECT COUNT(*) FROM users WHERE is_active = 1) as total_active_users,
        (SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)) as new_users_month,
        (SELECT COUNT(*) FROM user_approvals WHERE approval_status = 'pending') as pending_approvals,
        (SELECT COUNT(*) FROM products WHERE status = 'available') as active_products,
        (SELECT COUNT(*) FROM orders WHERE status = 'pending') as pending_orders,
        (SELECT COUNT(*) FROM reports WHERE status = 'pending') as pending_reports,
        (SELECT COUNT(DISTINCT admin_id) FROM admin_activity_log WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)) as active_admins_today;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetDashboardStats` (IN `userId` INT)   BEGIN
    SELECT 
        (SELECT COUNT(*) FROM enterprises WHERE farm_id IN (SELECT id FROM farms WHERE user_id = userId)) as total_enterprises,
        (SELECT COALESCE(SUM(total_acres), 0) FROM farms WHERE user_id = userId) as total_acres,
        (SELECT COUNT(*) FROM products WHERE seller_id = userId AND status = 'available') as active_listings,
        (SELECT COUNT(*) FROM notifications WHERE user_id = userId AND is_read = 0) as unread_notifications,
        (SELECT COALESCE(SUM(CASE WHEN transaction_type = 'income' THEN amount ELSE 0 END), 0) FROM transactions WHERE user_id = userId AND MONTH(transaction_date) = MONTH(CURDATE())) as monthly_income,
        (SELECT COALESCE(SUM(CASE WHEN transaction_type = 'expense' THEN amount ELSE 0 END), 0) FROM transactions WHERE user_id = userId AND MONTH(transaction_date) = MONTH(CURDATE())) as monthly_expenses,
        (SELECT COUNT(*) FROM orders WHERE buyer_id = userId AND status = 'pending') as pending_orders,
        (SELECT COUNT(*) FROM favorites WHERE user_id = userId) as wishlist_count;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetDistrictsByRegion` (IN `regionId` INT)   BEGIN
    SELECT id, district_name, district_code
    FROM districts
    WHERE region_id = regionId
    ORDER BY district_name;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetLocationDetails` (IN `villageId` INT)   BEGIN
    SELECT 
        r.region_name,
        d.district_name,
        s.subcounty_name,
        p.parish_name,
        v.village_name
    FROM villages v
    JOIN parishes p ON v.parish_id = p.id
    JOIN subcounties s ON p.subcounty_id = s.id
    JOIN districts d ON s.district_id = d.id
    JOIN regions r ON d.region_id = r.id
    WHERE v.id = villageId;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetParishesBySubcounty` (IN `subcountyId` INT)   BEGIN
    SELECT id, parish_name, parish_code
    FROM parishes
    WHERE subcounty_id = subcountyId
    ORDER BY parish_name;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetPendingApprovals` (IN `userType` VARCHAR(50))   BEGIN
    SELECT 
        ua.*,
        u.full_name,
        u.phone_number,
        u.email,
        u.created_at as registration_date
    FROM user_approvals ua
    JOIN users u ON ua.user_id = u.id
    WHERE ua.approval_status = 'pending'
        AND (userType IS NULL OR ua.user_type = userType)
    ORDER BY ua.created_at DESC;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetSubcountiesByDistrict` (IN `districtId` INT)   BEGIN
    SELECT id, subcounty_name, subcounty_code
    FROM subcounties
    WHERE district_id = districtId
    ORDER BY subcounty_name;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetUnreadMessageCount` (IN `userId` INT)   BEGIN
    SELECT 
        c.id as chat_id,
        c.chat_name,
        c.chat_type,
        COUNT(m.id) as unread_count,
        MAX(m.created_at) as last_message_time
    FROM chats c
    INNER JOIN chat_members cm ON c.id = cm.chat_id
    LEFT JOIN messages m ON c.id = m.chat_id 
        AND m.created_at > COALESCE(cm.last_read_at, '2000-01-01')
        AND m.sender_id != userId
    WHERE cm.user_id = userId
    GROUP BY c.id, c.chat_name, c.chat_type
    HAVING unread_count > 0
    ORDER BY last_message_time DESC;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetUserPermissions` (IN `userId` INT)   BEGIN
    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 = userId AND ar.is_active = 1
    ORDER BY p.permission_category, p.permission_name;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetUserProfile` (IN `p_user_id` INT, IN `p_viewer_id` INT)   BEGIN
    -- Set session variables for tracking (if provided)
    -- These are used by triggers/logging
    
    SELECT 
        -- Basic user info
        u.id,
        u.phone_number,
        u.full_name,
        u.email,
        u.user_type,
        u.is_verified,
        
        -- IMPORTANT: Return RELATIVE paths, NOT full URLs
        u.profile_picture,
        
        u.created_at AS joined_date,  -- Fix: created_at not joined_date
        u.last_login,
        
        -- Location info
        r.region_name,
        d.district_name,
        s.subcounty_name,
        p.parish_name,
        v.village_name,
        
        -- Profile extended data
        up.bio,
        up.tagline,
        up.about_me,
        
        -- IMPORTANT: Return RELATIVE path, NOT full URL
        up.cover_photo,
        
        up.date_of_birth,
        up.gender,
        up.occupation,
        up.education_level,
        up.years_in_farming,
        up.farm_size_acres,
        up.farming_type,
        up.profile_views,
        up.profile_completeness,
        up.facebook_url,
        up.twitter_url,
        up.instagram_url,
        up.linkedin_url,
        up.youtube_url,
        up.show_phone,
        up.show_location,
        up.show_email,
        up.show_birthday,
        up.profile_visibility,
        
        -- Additional fields
        up.secondary_phone,
        up.whatsapp_number,
        up.website,
        up.interests,
        up.skills,
        up.languages,
        up.crops_grown,
        up.livestock_kept,
        
        -- Counts and stats
        (SELECT COUNT(*) FROM friendships 
         WHERE (user_id = p_user_id OR friend_id = p_user_id) 
         AND status = 'accepted') AS friends_count,
        
        (SELECT COUNT(*) FROM products 
         WHERE seller_id = p_user_id AND status = 'available') AS active_products_count,
        
        (SELECT COUNT(*) FROM posts WHERE user_id = p_user_id) AS posts_count,
        
        (SELECT COALESCE(AVG(rating), 0) FROM reviews WHERE reviewed_user_id = p_user_id) AS average_rating,
        
        (SELECT COUNT(*) FROM reviews WHERE reviewed_user_id = p_user_id) AS review_count,
        
        (SELECT COUNT(*) FROM user_achievements WHERE user_id = p_user_id) AS achievements_count,
        
        (SELECT COUNT(*) FROM profile_photos 
         WHERE user_id = p_user_id AND photo_type = 'gallery') AS photos_count,
        
        -- Privacy-aware fields (only show if privacy allows OR viewer is the user themselves)
        CASE 
            WHEN up.show_phone = 1 OR p_viewer_id = p_user_id THEN u.phone_number
            ELSE NULL 
        END AS visible_phone,
        
        CASE 
            WHEN up.show_email = 1 OR p_viewer_id = p_user_id THEN u.email
            ELSE NULL 
        END AS visible_email,
        
        CASE 
            WHEN up.show_location = 1 OR p_viewer_id = p_user_id THEN 
                CONCAT_WS(', ', 
                    NULLIF(v.village_name, ''), 
                    NULLIF(p.parish_name, ''), 
                    NULLIF(s.subcounty_name, ''), 
                    NULLIF(d.district_name, '')
                )
            ELSE NULL 
        END AS visible_location,
        
        CASE 
            WHEN up.show_birthday = 1 OR p_viewer_id = p_user_id THEN up.date_of_birth
            ELSE NULL 
        END AS visible_birthday,
        
        -- Friend status
        (SELECT COUNT(*) FROM friendships 
         WHERE ((user_id = p_viewer_id AND friend_id = p_user_id) 
                OR (user_id = p_user_id AND friend_id = p_viewer_id))
         AND status = 'accepted') AS is_friend,
        
        -- Is this the user viewing their own profile?
        CASE WHEN p_viewer_id = p_user_id THEN 1 ELSE 0 END AS is_self
        
    FROM users u
    LEFT JOIN user_profiles up ON u.id = up.user_id
    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
    WHERE u.id = p_user_id;
    
    -- Log profile view (optional - only if viewer is different from profile owner)
    IF p_viewer_id IS NOT NULL AND p_viewer_id != p_user_id THEN
        INSERT INTO profile_views (profile_user_id, visitor_user_id, ip_address, user_agent)
        VALUES (
            p_user_id, 
            p_viewer_id,
            @current_ip_address,
            @current_user_agent
        );
    END IF;
    
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetUserPublicKey` (IN `p_user_id` INT)   BEGIN
    SELECT public_key, fingerprint 
    FROM user_encryption_keys 
    WHERE user_id = p_user_id;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetUserRating` (IN `userId` INT)   BEGIN
    SELECT 
        COALESCE(AVG(rating), 0) as average_rating,
        COUNT(*) as total_reviews
    FROM reviews
    WHERE reviewed_user_id = userId;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `GetVillagesByParish` (IN `parishId` INT)   BEGIN
    SELECT id, village_name, village_code
    FROM villages
    WHERE parish_id = parishId
    ORDER BY village_name;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `get_ai_stats` (IN `p_user_id` INT)   BEGIN
    SELECT 
        COUNT(DISTINCT session_id) as total_conversations,
        COUNT(*) as total_messages,
        SUM(CASE WHEN language = 'lusoga' THEN 1 ELSE 0 END) as lusoga_count,
        SUM(CASE WHEN language = 'en' THEN 1 ELSE 0 END) as english_count,
        SUM(CASE WHEN source = 'openai' THEN 1 ELSE 0 END) as openai_count,
        SUM(CASE WHEN source = 'rule_based' THEN 1 ELSE 0 END) as rule_based_count,
        SUM(CASE WHEN source = 'knowledge_base' THEN 1 ELSE 0 END) as knowledge_base_count,
        SUM(CASE WHEN source = 'database' THEN 1 ELSE 0 END) as database_count,
        MIN(created_at) as first_conversation,
        MAX(created_at) as last_conversation,
        ROUND(AVG(CHAR_LENGTH(response)), 0) as avg_response_length
    FROM ai_conversations 
    WHERE user_id = p_user_id;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `get_user_sessions` (IN `p_user_id` INT, IN `p_limit` INT)   BEGIN
    SELECT 
        session_id,
        MIN(created_at) as started_at,
        MAX(created_at) as last_message_at,
        COUNT(*) as message_count,
        (SELECT message FROM ai_conversations ac2 
         WHERE ac2.session_id = ac.session_id 
         ORDER BY created_at ASC LIMIT 1) as first_message,
        (SELECT message FROM ai_conversations ac2 
         WHERE ac2.session_id = ac.session_id 
         ORDER BY created_at DESC LIMIT 1) as last_message
    FROM ai_conversations ac
    WHERE user_id = p_user_id 
      AND session_id IS NOT NULL
    GROUP BY session_id
    ORDER BY last_message_at DESC
    LIMIT p_limit;
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `LogAdminActivity` (IN `p_admin_id` INT, IN `p_action_type` VARCHAR(100), IN `p_description` TEXT, IN `p_table` VARCHAR(50), IN `p_record_id` INT, IN `p_ip_address` VARCHAR(45))   BEGIN
    INSERT INTO admin_activity_log 
        (admin_id, action_type, action_description, affected_table, affected_record_id, ip_address)
    VALUES 
        (p_admin_id, p_action_type, p_description, p_table, p_record_id, p_ip_address);
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `LogEncryptionAction` (IN `p_user_id` INT, IN `p_action_type` VARCHAR(50), IN `p_description` TEXT, IN `p_ip_address` VARCHAR(45), IN `p_user_agent` TEXT)   BEGIN
    INSERT INTO encryption_audit_log 
        (user_id, action_type, description, ip_address, user_agent)
    VALUES 
        (p_user_id, p_action_type, p_description, p_ip_address, p_user_agent);
END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `sync_all_role_permissions` ()   BEGIN
        DECLARE done INT DEFAULT FALSE;
        DECLARE current_role_id INT;
        DECLARE current_role_level INT;
        DECLARE role_cursor CURSOR FOR SELECT id, role_level FROM admin_roles WHERE is_active = 1;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
        OPEN role_cursor;
        read_loop: LOOP
            FETCH role_cursor INTO current_role_id, current_role_level;
            IF done THEN LEAVE read_loop; END IF;
            CALL sync_role_permissions(current_role_id);
        END LOOP;
        CLOSE role_cursor;
    END$$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `sync_role_permissions` (IN `role_id_param` INT)   BEGIN
        DECLARE role_level_val INT;
        SELECT role_level INTO role_level_val FROM admin_roles WHERE id = role_id_param;
        IF role_level_val >= 10 THEN
            INSERT INTO role_permissions (role_id, permission_id, granted_at, granted_by)
            SELECT role_id_param, id, NOW(), @current_admin_id FROM admin_permissions
            ON DUPLICATE KEY UPDATE granted_at = NOW();
        ELSEIF role_level_val >= 8 THEN
            INSERT INTO role_permissions (role_id, permission_id, granted_at, granted_by)
            SELECT role_id_param, id, NOW(), @current_admin_id FROM admin_permissions
            WHERE permission_key NOT IN ('full_access', 'manage_roles', 'delete_users')
            ON DUPLICATE KEY UPDATE granted_at = NOW();
        END IF;
    END$$

--
-- Functions
--
CREATE DEFINER=`root`@`127.0.0.1` FUNCTION `get_or_create_one_on_one_chat` (`user1_id` INT, `user2_id` INT) RETURNS INT(11) DETERMINISTIC BEGIN
    DECLARE existing_chat_id INT;
    DECLARE new_chat_id INT;
    
    -- Check if chat already exists
    SELECT c.id INTO existing_chat_id
    FROM chats c
    INNER JOIN chat_members cm1 ON c.id = cm1.chat_id AND cm1.user_id = user1_id
    INNER JOIN chat_members cm2 ON c.id = cm2.chat_id AND cm2.user_id = user2_id
    WHERE c.chat_type = 'one_to_one'
    LIMIT 1;
    
    IF existing_chat_id IS NOT NULL THEN
        RETURN existing_chat_id;
    END IF;
    
    -- Create new chat
    INSERT INTO chats (chat_type, created_by, created_at, updated_at)
    VALUES ('one_to_one', user1_id, NOW(), NOW());
    
    SET new_chat_id = LAST_INSERT_ID();
    
    -- Add both members
    INSERT INTO chat_members (chat_id, user_id, role, joined_at)
    VALUES 
        (new_chat_id, user1_id, 'member', NOW()),
        (new_chat_id, user2_id, 'member', NOW());
    
    RETURN new_chat_id;
END$$

CREATE DEFINER=`root`@`127.0.0.1` FUNCTION `user_has_permission` (`user_id_param` INT, `permission_key_param` VARCHAR(50)) RETURNS TINYINT(1) DETERMINISTIC READS SQL DATA BEGIN
    DECLARE has_perm BOOLEAN DEFAULT FALSE;
    DECLARE user_role_id INT;
    DECLARE user_role_level INT;
    
    -- Get user's role
    SELECT admin_role_id INTO user_role_id
    FROM users
    WHERE id = user_id_param;
    
    IF user_role_id IS NULL THEN
        RETURN FALSE;
    END IF;
    
    -- Check role level
    SELECT role_level INTO user_role_level
    FROM admin_roles
    WHERE id = user_role_id;
    
    -- Super Admin has all permissions
    IF user_role_level >= 10 THEN
        RETURN TRUE;
    END IF;
    
    -- Check specific permission
    SELECT EXISTS(
        SELECT 1
        FROM role_permissions rp
        JOIN admin_permissions ap ON rp.permission_id = ap.id
        WHERE rp.role_id = user_role_id
        AND ap.permission_key = permission_key_param
    ) INTO has_perm;
    
    RETURN has_perm;
END$$

DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `activity_log`
--

CREATE TABLE `activity_log` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `action` varchar(100) NOT NULL,
  `description` text DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `activity_log`
--

INSERT INTO `activity_log` (`id`, `user_id`, `action`, `description`, `ip_address`, `user_agent`, `created_at`) VALUES
(1, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-26 20:03:59'),
(2, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-26 21:51:02'),
(3, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-26 22:33:20'),
(4, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-26 22:33:45'),
(5, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-27 07:57:47'),
(6, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-27 08:08:49'),
(7, 9, 'verify_otp', 'Phone number verified and logged in', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36', '2026-01-27 08:11:09'),
(8, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36', '2026-01-27 09:23:27'),
(9, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-27 19:07:09'),
(10, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-27 21:33:08'),
(11, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-27 22:17:32'),
(12, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-27 22:17:59'),
(13, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-28 16:48:14'),
(14, 3, 'download_resource', 'Downloaded resource ID: 1', NULL, NULL, '2026-01-28 17:03:50'),
(15, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-29 09:25:42'),
(16, 3, 'add_product', 'Added product: Fresh Beans for Sale', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-29 10:04:06'),
(17, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-29 13:35:36'),
(18, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-30 06:42:52'),
(19, 3, 'create_farm', 'Created farm: My Farm', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-30 07:02:06'),
(20, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-30 18:34:20'),
(21, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-30 21:13:55'),
(22, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 OPR/125.0.0.0', '2026-01-31 04:35:17'),
(23, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 04:37:27'),
(24, 3, 'update_product_status', 'Changed product ID 1 to available', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 06:16:30'),
(25, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 06:52:13'),
(26, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 09:27:13'),
(27, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 12:49:13'),
(28, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 13:19:25'),
(29, 9, 'create_farm', 'Created farm: My Farm', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 13:25:04'),
(30, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-01-31 15:20:39'),
(31, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 07:31:27'),
(32, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 09:43:28'),
(33, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 12:26:01'),
(34, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 16:40:52'),
(35, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 18:26:57'),
(36, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 19:00:49'),
(37, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 21:18:15'),
(38, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 21:49:37'),
(39, 3, 'create_enterprise', 'Created enterprise: sugar_cane', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 21:51:49'),
(40, 3, 'create_transaction', 'expense transaction: UGX 6,000,000', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 22:00:43'),
(41, 3, 'create_transaction', 'expense transaction: UGX 720,000', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-01 22:02:47'),
(42, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 09:14:01'),
(43, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 11:22:46'),
(44, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 14:35:54'),
(45, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 15:39:25'),
(46, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 15:56:24'),
(47, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 17:22:48'),
(48, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-02 19:20:07'),
(49, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 19:38:00'),
(50, 3, 'update_farm', 'Updated farm ID: 1', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 19:54:43'),
(51, 3, 'update_farm', 'Updated farm ID: 1', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 19:55:15'),
(52, 3, 'update_farm', 'Updated farm ID: 1', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 19:55:19'),
(53, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-02 21:28:08'),
(54, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 07:01:53'),
(55, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 09:44:59'),
(56, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 11:00:18'),
(57, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-03 12:20:48'),
(58, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 14:29:13'),
(59, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 14:42:27'),
(60, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 14:47:49'),
(61, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 16:33:33'),
(62, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 16:50:50'),
(63, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-03 16:51:14'),
(64, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 05:41:33'),
(65, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 09:47:47'),
(66, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 14:59:13'),
(67, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 18:09:40'),
(68, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 18:42:42'),
(69, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-04 19:16:24'),
(70, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 04:34:14'),
(71, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 04:44:39'),
(72, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 05:04:37'),
(73, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 06:22:00'),
(74, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 06:24:30'),
(75, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 06:26:00'),
(76, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 06:36:41'),
(77, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 06:47:02'),
(78, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 09:44:22'),
(79, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 12:34:18'),
(80, 2, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 18:41:53'),
(81, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 20:16:38'),
(82, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 20:27:59'),
(83, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 20:29:14'),
(84, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 20:58:55'),
(85, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-05 21:21:10'),
(86, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 05:49:40'),
(87, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 05:50:25'),
(88, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 05:55:30'),
(89, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 06:27:41'),
(90, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 17:16:08'),
(91, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-06 17:46:33'),
(92, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-06 19:06:01'),
(93, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-06 19:16:06'),
(94, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 05:40:22'),
(95, 3, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0', '2026-02-07 06:24:09'),
(96, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:26:43'),
(97, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:27:13'),
(98, 9, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:32:51'),
(99, 4, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:34:32'),
(100, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 07:45:38'),
(101, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 08:15:35'),
(102, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 12:10:31'),
(103, 5, 'login', 'User logged in successfully', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 12:16:42');

--
-- Triggers `activity_log`
--
DELIMITER $$
CREATE TRIGGER `increment_product_views` AFTER INSERT ON `activity_log` FOR EACH ROW BEGIN
    IF NEW.action = 'view_product' THEN
        UPDATE products 
        SET views = views + 1 
        WHERE id = CAST(SUBSTRING_INDEX(NEW.description, ':', -1) AS UNSIGNED);
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `admin_activity_log`
--

CREATE TABLE `admin_activity_log` (
  `id` int(11) NOT NULL,
  `admin_id` int(11) NOT NULL,
  `action_type` varchar(100) NOT NULL,
  `action_description` text DEFAULT NULL,
  `affected_table` varchar(50) DEFAULT NULL,
  `affected_record_id` int(11) DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `request_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Stores request parameters' CHECK (json_valid(`request_data`)),
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `admin_activity_log`
--

INSERT INTO `admin_activity_log` (`id`, `admin_id`, `action_type`, `action_description`, `affected_table`, `affected_record_id`, `ip_address`, `user_agent`, `request_data`, `created_at`) VALUES
(1, 5, 'update', 'Updated admin user details', 'users', 5, NULL, NULL, NULL, '2026-02-07 07:49:20'),
(2, 5, 'grant_permission', 'Granted \"Moderate Content\" permission to \"Super Administrator\" role', 'role_permissions', 82, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(3, 5, 'grant_permission', 'Granted \"View Encrypted Messages\" permission to \"Super Administrator\" role', 'role_permissions', 83, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(4, 5, 'grant_permission', 'Granted \"View Server Statistics\" permission to \"Super Administrator\" role', 'role_permissions', 84, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(5, 5, 'grant_permission', 'Granted \"Manage Server\" permission to \"Super Administrator\" role', 'role_permissions', 85, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(6, 5, 'grant_permission', 'Granted \"View Network Usage\" permission to \"Super Administrator\" role', 'role_permissions', 86, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(7, 5, 'grant_permission', 'Granted \"Manage Backups\" permission to \"Super Administrator\" role', 'role_permissions', 87, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(8, 5, 'grant_permission', 'Granted \"View Security Logs\" permission to \"Super Administrator\" role', 'role_permissions', 88, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(9, 5, 'grant_permission', 'Granted \"Manage Security\" permission to \"Super Administrator\" role', 'role_permissions', 89, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(10, 5, 'grant_permission', 'Granted \"View Audit Logs\" permission to \"Super Administrator\" role', 'role_permissions', 90, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(11, 5, 'grant_permission', 'Granted \"Manage Email Configuration\" permission to \"Super Administrator\" role', 'role_permissions', 91, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(12, 5, 'grant_permission', 'Granted \"Manage Maintenance Mode\" permission to \"Super Administrator\" role', 'role_permissions', 92, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(13, 5, 'grant_permission', 'Granted \"Manage Backups\" permission to \"Administrator\" role', 'role_permissions', 97, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(14, 5, 'grant_permission', 'Granted \"Manage Email Configuration\" permission to \"Administrator\" role', 'role_permissions', 98, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(15, 5, 'grant_permission', 'Granted \"Manage Maintenance Mode\" permission to \"Administrator\" role', 'role_permissions', 99, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(16, 5, 'grant_permission', 'Granted \"Manage Security\" permission to \"Administrator\" role', 'role_permissions', 100, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(17, 5, 'grant_permission', 'Granted \"Moderate Content\" permission to \"Administrator\" role', 'role_permissions', 101, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(18, 5, 'grant_permission', 'Granted \"View Audit Logs\" permission to \"Administrator\" role', 'role_permissions', 102, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(19, 5, 'grant_permission', 'Granted \"View Encrypted Messages\" permission to \"Administrator\" role', 'role_permissions', 103, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(20, 5, 'grant_permission', 'Granted \"View Network Usage\" permission to \"Administrator\" role', 'role_permissions', 104, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(21, 5, 'grant_permission', 'Granted \"View Security Logs\" permission to \"Administrator\" role', 'role_permissions', 105, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(22, 5, 'grant_permission', 'Granted \"View Server Statistics\" permission to \"Administrator\" role', 'role_permissions', 106, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(23, 5, 'sync_permissions', 'Synchronized permissions for all roles. Total roles: 5', 'role_permissions', NULL, NULL, NULL, NULL, '2026-02-07 07:59:21'),
(24, 5, 'grant_permission', 'Granted \"Manage Server\" to \"Administrator\"', 'role_permissions', 113, NULL, NULL, NULL, '2026-02-07 08:08:38');

-- --------------------------------------------------------

--
-- Table structure for table `admin_permissions`
--

CREATE TABLE `admin_permissions` (
  `id` int(11) NOT NULL,
  `permission_key` varchar(50) NOT NULL,
  `permission_name` varchar(100) NOT NULL,
  `permission_description` text DEFAULT NULL,
  `permission_category` enum('users','content','system','data','reports') DEFAULT 'system',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `admin_permissions`
--

INSERT INTO `admin_permissions` (`id`, `permission_key`, `permission_name`, `permission_description`, `permission_category`, `created_at`) VALUES
(1, 'view_dashboard', 'View Dashboard', 'Access to admin dashboard', 'system', '2026-01-26 21:54:57'),
(2, 'view_analytics', 'View Analytics', 'Access to analytics and statistics', 'reports', '2026-01-26 21:54:57'),
(3, 'view_logs', 'View System Logs', 'Access to system and activity logs', 'system', '2026-01-26 21:54:57'),
(4, 'manage_users', 'Manage Users', 'Create, edit, view user accounts', 'users', '2026-01-26 21:54:57'),
(5, 'approve_users', 'Approve Users', 'Approve or reject user registrations', 'users', '2026-01-26 21:54:57'),
(6, 'delete_users', 'Delete Users', 'Permanently delete user accounts', 'users', '2026-01-26 21:54:57'),
(7, 'ban_users', 'Ban Users', 'Ban or suspend user accounts', 'users', '2026-01-26 21:54:57'),
(8, 'export_users', 'Export User Data', 'Export user data to files', 'users', '2026-01-26 21:54:57'),
(9, 'manage_locations', 'Manage Locations', 'CRUD operations on location hierarchy', 'data', '2026-01-26 21:54:57'),
(10, 'import_locations', 'Import Locations', 'Bulk import location data', 'data', '2026-01-26 21:54:57'),
(11, 'manage_products', 'Manage Products', 'Moderate and manage marketplace products', 'content', '2026-01-26 21:54:57'),
(12, 'delete_products', 'Delete Products', 'Remove products from marketplace', 'content', '2026-01-26 21:54:57'),
(13, 'view_orders', 'View Orders', 'View all system orders', 'data', '2026-01-26 21:54:57'),
(14, 'manage_orders', 'Manage Orders', 'Update order statuses', 'data', '2026-01-26 21:54:57'),
(15, 'manage_prices', 'Manage Market Prices', 'Add, edit, delete market prices', 'content', '2026-01-26 21:54:57'),
(16, 'import_prices', 'Import Prices', 'Bulk import market price data', 'content', '2026-01-26 21:54:57'),
(17, 'manage_content', 'Manage Content', 'Manage tips, resources, and content', 'content', '2026-01-26 21:54:57'),
(18, 'publish_content', 'Publish Content', 'Approve and publish content', 'content', '2026-01-26 21:54:57'),
(19, 'manage_reports', 'Manage Reports', 'Review and resolve user reports', 'users', '2026-01-26 21:54:57'),
(20, 'view_reports', 'View Reports', 'Access to user-submitted reports', 'users', '2026-01-26 21:54:57'),
(21, 'manage_settings', 'Manage Settings', 'Configure system settings', 'system', '2026-01-26 21:54:57'),
(22, 'manage_roles', 'Manage Roles & Permissions', 'Configure admin roles and permissions', 'system', '2026-01-26 21:54:57'),
(23, 'full_access', 'Full System Access', 'Complete unrestricted access', 'system', '2026-01-26 21:54:57'),
(24, 'view_server_stats', 'View Server Statistics', 'View server performance metrics and status', 'system', '2026-02-07 07:47:50'),
(25, 'manage_server', 'Manage Server', 'Full server management including database operations', 'system', '2026-02-07 07:47:50'),
(26, 'view_network_usage', 'View Network Usage', 'Monitor network traffic and usage statistics', 'system', '2026-02-07 07:47:50'),
(27, 'manage_backups', 'Manage Backups', 'Create, restore, and manage database backups', 'system', '2026-02-07 07:47:50'),
(28, 'view_security_logs', 'View Security Logs', 'Access security logs and threat detection', 'system', '2026-02-07 07:47:50'),
(29, 'manage_security', 'Manage Security', 'Configure security settings, firewall, and IP controls', 'system', '2026-02-07 07:47:50'),
(30, 'view_audit_logs', 'View Audit Logs', 'Access system audit trail and admin activity logs', 'system', '2026-02-07 07:47:50'),
(31, 'moderate_content', 'Moderate Content', 'Review and action reported content', 'content', '2026-02-07 07:47:50'),
(32, 'view_encrypted_messages', 'View Encrypted Messages', 'Access reported encrypted messages (requires special authorization)', 'content', '2026-02-07 07:47:50'),
(33, 'manage_email_config', 'Manage Email Configuration', 'Configure email settings and templates', 'system', '2026-02-07 07:47:50'),
(34, 'manage_maintenance', 'Manage Maintenance Mode', 'Enable/disable system maintenance mode', 'system', '2026-02-07 07:47:50');

--
-- Triggers `admin_permissions`
--
DELIMITER $$
CREATE TRIGGER `sync_admin_permissions_on_new_permission` AFTER INSERT ON `admin_permissions` FOR EACH ROW BEGIN
    DECLARE admin_role_id INT;

    SELECT id INTO admin_role_id
    FROM admin_roles
    WHERE role_level = 8 AND is_active = 1
    LIMIT 1;

    IF admin_role_id IS NOT NULL
       AND NEW.permission_key NOT IN
           ('full_access','manage_roles','delete_users','manage_server') THEN

        INSERT IGNORE INTO role_permissions
            (role_id, permission_id, granted_at, granted_by)
        VALUES
            (admin_role_id, NEW.id, NOW(), @current_admin_id);
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `sync_super_admin_permissions_on_new_permission` AFTER INSERT ON `admin_permissions` FOR EACH ROW BEGIN
    DECLARE super_admin_role_id INT;

    SELECT id INTO super_admin_role_id
    FROM admin_roles
    WHERE role_level >= 10 AND is_active = 1
    LIMIT 1;

    IF super_admin_role_id IS NOT NULL THEN
        INSERT IGNORE INTO role_permissions
            (role_id, permission_id, granted_at, granted_by)
        VALUES
            (super_admin_role_id, NEW.id, NOW(), @current_admin_id);

        INSERT INTO admin_activity_log
            (admin_id, action_type, action_description, affected_table, affected_record_id)
        VALUES
            (COALESCE(@current_admin_id, 1),
             'auto_permission_grant',
             CONCAT('Auto-granted "', NEW.permission_name, '" to Super Admin'),
             'role_permissions',
             NEW.id);
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `admin_roles`
--

CREATE TABLE `admin_roles` (
  `id` int(11) NOT NULL,
  `role_name` varchar(50) NOT NULL,
  `role_description` text DEFAULT NULL,
  `role_level` int(11) DEFAULT 1 COMMENT '1-Low, 5-Medium, 10-Super Admin',
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `admin_roles`
--

INSERT INTO `admin_roles` (`id`, `role_name`, `role_description`, `role_level`, `is_active`, `created_at`, `updated_at`) VALUES
(1, 'Super Administrator', 'Full system access with all permissions', 10, 1, '2026-01-26 21:54:57', '2026-01-26 21:54:57'),
(2, 'Administrator', 'High-level access for day-to-day administration', 8, 1, '2026-01-26 21:54:57', '2026-01-26 21:54:57'),
(3, 'Content Manager', 'Manages agricultural tips, prices, and content', 5, 1, '2026-01-26 21:54:57', '2026-01-26 21:54:57'),
(4, 'User Moderator', 'Manages users, approvals, and reports', 5, 1, '2026-01-26 21:54:57', '2026-01-26 21:54:57'),
(5, 'Data Analyst', 'View-only access to analytics and reports', 3, 1, '2026-01-26 21:54:57', '2026-01-26 21:54:57');

--
-- Triggers `admin_roles`
--
DELIMITER $$
CREATE TRIGGER `assign_default_permissions_on_new_role` AFTER INSERT ON `admin_roles` FOR EACH ROW BEGIN
    -- Every role gets dashboard access
    INSERT IGNORE INTO role_permissions
        (role_id, permission_id, granted_at, granted_by)
    SELECT
        NEW.id, id, NOW(), @current_admin_id
    FROM admin_permissions
    WHERE permission_key = 'view_dashboard';

    -- Super Admin gets everything
    IF NEW.role_level >= 10 THEN
        INSERT IGNORE INTO role_permissions
            (role_id, permission_id, granted_at, granted_by)
        SELECT
            NEW.id, id, NOW(), @current_admin_id
        FROM admin_permissions;
    END IF;

    INSERT INTO admin_activity_log
        (admin_id, action_type, action_description, affected_table, affected_record_id)
    VALUES
        (COALESCE(@current_admin_id, 1),
         'create_role',
         CONCAT('Created role: ', NEW.role_name),
         'admin_roles',
         NEW.id);
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `agricultural_tips`
--

CREATE TABLE `agricultural_tips` (
  `id` int(11) NOT NULL,
  `title` varchar(200) NOT NULL,
  `content` text NOT NULL,
  `category` enum('crop_management','pest_control','soil_health','irrigation','harvesting','storage','general') NOT NULL,
  `crop_type` varchar(50) DEFAULT NULL,
  `season` varchar(50) DEFAULT NULL,
  `language` enum('en','lusoga') DEFAULT 'en',
  `media_url` varchar(255) DEFAULT NULL,
  `created_by` int(11) DEFAULT NULL,
  `is_published` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `agricultural_tips`
--

INSERT INTO `agricultural_tips` (`id`, `title`, `content`, `category`, `crop_type`, `season`, `language`, `media_url`, `created_by`, `is_published`, `created_at`, `updated_at`) VALUES
(1, 'Best Time to Plant Maize', 'Plant maize at the beginning of the rainy season (March-April or September-October). Ensure soil moisture is adequate before planting.', 'crop_management', 'maize', NULL, 'en', NULL, NULL, 1, '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(2, 'Sugar Cane Pest Control', 'Monitor for stem borers and apply appropriate pesticides early. Keep the field clean and remove infected plants immediately.', 'pest_control', 'sugar_cane', NULL, 'en', NULL, NULL, 1, '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(3, 'Poultry Disease Prevention', 'Vaccinate birds regularly, maintain clean housing, provide clean water, and isolate sick birds immediately.', 'pest_control', 'poultry', NULL, 'en', NULL, NULL, 1, '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(4, 'Proper Way to Apply Fertilizer', '**Follow these steps for effective fertilizer application:**\n\r\n\n\r\n- **Timing:** Apply basal fertilizer (DAP) at planting. Apply top dressing (Urea) 3-4 weeks after planting when maize is knee-high.\n\r\n- **Method:** Make a small furrow 5-10cm from the plant base. Place fertilizer in furrow and cover with soil. Don\'t let fertilizer touch plant stems.\n\r\n- **Moisture:** Apply when soil has moisture. If dry, water lightly after application.\n\r\n- **Amount:** Use recommended rates - typically 50kg DAP and 50kg Urea per acre for maize.\n\r\n- **Safety:** Wash hands after handling fertilizer. Store in dry place away from children.\n\r\n\n\r\n**Remember:** Too much fertilizer can burn plants. Too little won\'t give expected yields. Follow recommendations!', 'crop_management', 'maize', 'first_season', 'en', NULL, NULL, 1, '2026-02-02 19:33:20', '2026-02-03 11:00:40'),
(5, 'Organic Pest Control Methods', '**Natural ways to control pests without chemicals:**\n\r\n\n\r\n- **Neem Solution:** Crush neem seeds, soak in water overnight. Spray on plants to repel aphids and caterpillars.\n\r\n- **Wood Ash:** Sprinkle around plants to deter slugs and some insects. Also adds potassium to soil.\n\r\n- **Garlic & Chili Spray:** Blend garlic and hot chili with water. Strain and spray to repel many pests.\n\r\n- **Companion Planting:** Plant marigold or onions around crops to repel pests naturally.\n\r\n- **Hand Picking:** Remove large pests like caterpillars by hand early morning when they\'re less active.\n\r\n- **Ash & Soap Mix:** Mix wood ash with small amount of soap in water. Spray on aphids.\n\r\n\n\r\n**Tip:** Apply organic sprays in evening to avoid harming beneficial insects like bees.', 'pest_control', NULL, 'all_year', 'en', NULL, NULL, 1, '2026-02-02 19:33:20', '2026-02-03 11:00:40'),
(6, 'Making Quality Compost', '**Steps to make nutrient-rich compost:**\n\r\n**Materials Needed:**\n\r\n\n\r\n- Green materials (fresh grass, vegetable scraps, manure)\n\r\n- Brown materials (dry leaves, straw, crop residues)\n\r\n- Water\n\r\n- Space (3m x 3m minimum)\n\r\n\n\r\n**Process:**\n\r\n\n\r\n- Layer green and brown materials alternately (ratio 1:2)\n\r\n- Add water to each layer - should be moist like squeezed sponge\n\r\n- Build pile to at least 1 meter height\n\r\n- Turn pile every 2 weeks to add air\n\r\n- Cover with banana leaves or grass to retain moisture\n\r\n- Ready in 2-3 months when dark and crumbly\n\r\n\n\r\n**What NOT to add:**\n\r\n❌ Plastics ❌ Meat ❌ Oils ❌ Diseased plants', 'soil_health', NULL, 'all_year', 'en', NULL, NULL, 1, '2026-02-02 19:33:20', '2026-02-03 11:00:40'),
(7, 'Water Conservation Techniques', '**Save water and improve crop production:**\n\r\n**1. Mulching:**\n\r\nCover soil with grass, leaves, or crop residues. Reduces evaporation by up to 70%, keeps soil cool, suppresses weeds.\n\n\r\n**2. Basin Formation:**\n\r\nMake small basins around plants to capture and hold water near roots.\n\n\r\n**3. Drip Irrigation:**\n\r\nUse bottles or pipes with small holes to deliver water directly to roots. Saves up to 50% water compared to flooding.\n\n\r\n**4. Timing:**\n\r\nWater early morning or evening when evaporation is lowest. Avoid midday watering.\n\n\r\n**5. Rainwater Harvesting:**\n\r\nCollect roof runoff in tanks or ponds. Can provide water during dry spells.\n\n\r\n**Remember:** One good watering is better than several light waterings. Water deeply to encourage deep root growth.', 'irrigation', NULL, 'all_year', 'en', NULL, NULL, 1, '2026-02-02 19:33:20', '2026-02-03 11:00:40'),
(8, 'Post-Harvest Handling of Maize', '**Reduce losses after harvest:**\n\r\n**Proper Drying:**\n\r\n\n\r\n- Dry maize to 13-14% moisture content (kernels should be hard and difficult to dent with fingernail)\n\r\n- Spread on tarpaulin in sun - not directly on ground\n\r\n- Turn regularly for even drying\n\r\n- Takes 7-10 days depending on weather\n\r\n\n\r\n**Storage:**\n\r\n\n\r\n- Store in clean, dry, well-ventilated structure\n\r\n- Use proper storage bags or sealed containers\n\r\n- Add approved storage chemicals if needed\n\r\n- Keep away from moisture and pests\n\r\n- Stack bags on wooden pallets, not floor\n\r\n\n\r\n**Regular Monitoring:**\n\r\n\n\r\n- Check for moisture, pests, mold weekly\n\r\n- Remove any damaged grain immediately\n\r\n- Ensure good air circulation', 'storage', 'maize', 'all_year', 'en', NULL, NULL, 1, '2026-02-02 19:33:20', '2026-02-03 11:00:40'),
(9, 'Starting Layer Chicken Farming', '**Essential Requirements for 100 Layers:**\n\r\n\n\r\n- **Housing:** 50 sq meters, good ventilation, 1 nest box per 4-5 birds\n\r\n- **Chicks:** UGX 3,000 each from reputable hatchery\n\r\n- **Feed:** Starter (0-8 weeks), Grower (9-18 weeks), Layer mash (19+ weeks)\n\r\n- **Water:** Clean water always available, 2cm drinker space per bird\n\r\n- **Vaccination:** Day 1 Mareks, Week 1 ND+IB, Week 3&5 Gumboro, Week 6 ND booster\n\r\n\n\r\n**Expected Production:** 280-320 eggs per bird per year, starting at 18-20 weeks\n\n\r\n**Monthly Income (100 layers):** UGX 960,000 - 1,200,000 from 80 trays', 'general', 'poultry', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:40'),
(10, 'Broiler Chicken Production', '**6-Week Broiler Production Guide:**\n\r\n\n\r\n- **Chicks:** UGX 3,500 each, buy quality stock\n\r\n- **Feed per bird:** 5.4kg total (Starter 0.9kg, Grower 2.3kg, Finisher 2.2kg)\n\r\n- **Target weight:** 2.2-2.5kg at 6 weeks\n\r\n- **Stocking density:** 10-12 birds per square meter\n\r\n- **Temperature:** Week 1: 32-35°C, reduce by 3°C weekly\n\r\n\n\r\n**Profitability (100 birds):**\n\r\n\n\r\n- Investment: UGX 1,676,000\n\r\n- Revenue: UGX 1,672,000 - 2,090,000\n\r\n- Net profit: UGX 200,000 - 400,000 per cycle\n\r\n- Possible cycles per year: 6', 'general', 'poultry', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:40'),
(11, 'Preventing Poultry Diseases', '**Biosecurity and Disease Prevention:**\n\r\n**Critical Biosecurity Measures:**\n\r\n\n\r\n- **Footbaths:** Disinfectant at all entry points\n\r\n- **All-in, All-out:** Never mix age groups\n\r\n- **Quarantine:** Isolate new birds for 2 weeks\n\r\n- **Vaccination:** Follow strict schedule\n\r\n- **Cleanliness:** Daily water change, weekly litter management\n\r\n\n\r\n**Essential Vaccines:**\n\r\n\n\r\n- Newcastle Disease: Most important! Vaccinate regularly\n\r\n- Gumboro: Protects immune system\n\r\n- Infectious Bronchitis: Prevents respiratory issues\n\r\n- Fowl Pox: Especially in wet seasons\n\r\n- Mareks: At day old\n\r\n\n\r\n**Cost of prevention:** UGX 200-300 per bird\n\n\r\n**Cost of disease outbreak:** 50-100% mortality!', 'pest_control', 'poultry', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:40'),
(12, 'Making Your Own Poultry Feed', '**Homemade Layer Feed Recipe:**\n\r\n**For 100kg:**\n\n\r\n\n\r\n- Maize: 60kg (UGX 132,000)\n\r\n- Soybean meal: 20kg (UGX 60,000)\n\r\n- Fish meal: 5kg (UGX 15,000)\n\r\n- Wheat bran: 10kg (UGX 10,000)\n\r\n- Oyster shells: 3kg (UGX 6,000)\n\r\n- Salt: 0.5kg (UGX 500)\n\r\n- Premix: 0.5kg (UGX 5,000)\n\r\n- Total Cost: UGX 228,500 per 100kg\n\r\n\n\r\nCommercial feed costs UGX 170,000 per 50kg bag, so homemade saves about 33%!\n\n\r\n**Broiler Starter Recipe (100kg):**\n\r\n\n\r\n- Maize: 52kg\n\r\n- Soybean meal: 25kg\n\r\n- Fish meal: 10kg\n\r\n- Wheat bran: 8kg\n\r\n- Bone meal: 3kg\n\r\n- Salt: 0.5kg\n\r\n- Premix: 1.5kg\n\r\n\n\r\n**Important:** Grind all ingredients fine, mix thoroughly', 'general', 'poultry', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(13, 'Tomato Farming for Profit', '**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days', 'crop_management', 'vegetables', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(14, 'Profitable Cabbage Production', '**Growing Quality Cabbage:**\n\r\n**Best Varieties:**\n\r\n\n\r\n- **Gloria F1:** Large heads (2-3kg), disease resistant\n\r\n- **Blue Dynasty:** Very large (3-5kg), heat tolerant\n\r\n- **Copenhagen Market:** Good for processing\n\r\n\n\r\n**Planting Guide:**\n\r\n\n\r\n- Spacing: 60cm x 45cm (24,000 plants/acre)\n\r\n- Fertilizer: Base - 200kg DAP, Top - 150kg CAN (split)\n\r\n- Maturity: 90-120 days\n\r\n- Irrigation: Critical in dry months\n\r\n\n\r\n**Pest & Disease Management:**\n\r\n\n\r\n- **Diamond Back Moth:** Belt, Radiant weekly\n\r\n- **Aphids:** Confidor, neem oil\n\r\n- **Black Rot:** Copper-based fungicides\n\r\n- **Clubroot:** Lime soil, rotate crops\n\r\n\n\r\n**Marketing:**\n\r\nPrice: UGX 1,000-3,000 per head depending on season. Highest prices December-February.', 'crop_management', 'vegetables', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(15, 'Onion Farming Complete Guide', '**Onion Production for Market:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Red Creole:** Long storage, pungent, high yield\n\r\n- **Bombay Red:** Medium hot, good size\n\r\n- **Texas Early Grano:** Mild, early maturing\n\r\n\n\r\n**Nursery & Transplanting:**\n\r\n\n\r\n- Seed rate: 3-4kg per acre\n\r\n- Nursery period: 6-8 weeks\n\r\n- Transplant when pencil-thick\n\r\n- Spacing: 15cm x 10cm\n\r\n\n\r\n**Field Management:**\n\r\n\n\r\n- **Soil:** Well-drained, pH 6.0-7.0\n\r\n- **Fertilizer:** High potassium for bulb development\n\r\n- **Weeding:** Keep weed-free! Competes heavily\n\r\n- **Irrigation:** Regular until 2 weeks before harvest\n\r\n\n\r\n**Harvesting & Curing:**\n\r\n\n\r\n- Ready when tops fall over naturally\n\r\n- Cure in shade for 2-3 weeks\n\r\n- Store in ventilated room\n\r\n- Can store 3-6 months\n\r\n\n\r\n**Yields & Returns:**\n\r\n\n\r\n- Expected yield: 10-15 tons per acre\n\r\n- Price: UGX 2,000-5,000 per kg\n\r\n- Revenue: UGX 20-75 million per acre', 'crop_management', 'vegetables', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(16, 'Growing Indigenous Vegetables', '**Profitable African Leafy Vegetables:**\n\r\n**Popular Varieties:**\n\r\n\n\r\n- **Nakati (African Nightshade):** 30-40 days to harvest\n\r\n- **Dodo (Amaranth):** High in iron, 30-45 days\n\r\n- **Sukuma Wiki (Collards):** Multiple harvests\n\r\n- **Ethiopian Kale:** Heat tolerant\n\r\n\n\r\n**Advantages:**\n\r\n\n\r\n- Very quick maturity (30-45 days)\n\r\n- Multiple harvests from same plant\n\r\n- Low input requirements\n\r\n- High demand in local markets\n\r\n- Pest resistant\n\r\n- Highly nutritious\n\r\n\n\r\n**Production Guide:**\n\r\n\n\r\n- **Spacing:** 30cm x 20cm\n\r\n- **Fertilizer:** Manure + light NPK application\n\r\n- **Irrigation:** 2-3 times per week\n\r\n- **Harvesting:** Cut 10cm above ground, regrows\n\r\n\n\r\n**Economic Returns:**\n\r\n\n\r\n- Can harvest every 2-3 weeks\n\r\n- Bunches sell UGX 500-1,000 each\n\r\n- 4-6 tons fresh leaves per acre per month\n\r\n- Monthly income: UGX 2-4 million per acre', 'crop_management', 'vegetables', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(17, 'Hot Pepper & Sweet Pepper Farming', '**Growing Peppers for Profit:**\n\r\n**Types & Varieties:**\n\r\n**Hot Peppers:**\n\n\r\n\n\r\n- Bird\'s Eye (Pili Pili): Very hot, high demand\n\r\n- Cayenne: Medium hot\n\r\n- Habanero: Extremely hot, premium price\n\r\n\n\r\n**Sweet Peppers (Bell Peppers):**\n\n\r\n\n\r\n- California Wonder: Large fruits\n\r\n- Yolo Wonder: Disease resistant\n\r\n- Green/Red/Yellow varieties\n\r\n\n\r\n**Production Requirements:**\n\r\n\n\r\n- **Spacing:** 60cm x 45cm\n\r\n- **Fertilizer:** Heavy feeder like tomatoes\n\r\n- **Staking:** Recommended for heavy fruiting\n\r\n- **Irrigation:** Regular moisture needed\n\r\n- **Maturity:** 90-120 days\n\r\n\n\r\n**Pest & Disease:**\n\r\n\n\r\n- Aphids, Whiteflies: Use neem or chemical\n\r\n- Bacterial Wilt: Crop rotation essential\n\r\n- Anthracnose: Copper fungicides\n\r\n\n\r\n**Marketing:**\n\r\n\n\r\n- Hot peppers: UGX 3,000-8,000 per kg\n\r\n- Sweet peppers: UGX 2,000-5,000 per kg\n\r\n- Can be dried for longer storage\n\r\n- Export potential for quality produce', 'crop_management', 'vegetables', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(18, 'Starting a Dairy Farm', '**Dairy Cattle Farming Guide:**\n\r\n**Suitable Breeds for Uganda:**\n\r\n\n\r\n- **Friesian:** 20-30 liters/day, requires good management\n\r\n- **Jersey:** 15-20 liters/day, high butterfat\n\r\n- **Ayrshire:** 15-25 liters/day, hardy\n\r\n- **Crossbreeds:** Adapted to local conditions\n\r\n\n\r\n**Investment (1 in-milk cow):**\n\r\n\n\r\n- Cow purchase: UGX 2-4 million\n\r\n- Housing: UGX 1-2 million (simple shelter)\n\r\n- Equipment: UGX 500,000\n\r\n- Initial feed: UGX 300,000\n\r\n- Total: UGX 4-7 million\n\r\n\n\r\n**Daily Requirements per Cow:**\n\r\n\n\r\n- **Feed:** 50-70kg fresh grass/fodder\n\r\n- **Concentrate:** 1kg per 3 liters milk produced\n\r\n- **Water:** 60-80 liters per day\n\r\n- **Mineral supplement:** 50-100g daily\n\r\n\n\r\n**Monthly Economics (1 cow, 15 liters/day):**\n\r\n**Income:**\n\n\r\n\n\r\n- Milk: 450 liters × UGX 1,200 = UGX 540,000\n\r\n\n\r\n**Costs:**\n\n\r\n\n\r\n- Concentrate: UGX 150,000\n\r\n- Mineral supplement: UGX 15,000\n\r\n- Veterinary: UGX 20,000\n\r\n- Labor: UGX 50,000\n\r\n- Total: UGX 235,000\n\r\n\n\r\n**Net profit: UGX 305,000 per cow per month**\n\n\r\n**Health Management:**\n\r\n\n\r\n- Deworming: Every 3 months\n\r\n- Vaccination: FMD, LSD, Brucellosis\n\r\n- Tick control: Regular dipping/spraying\n\r\n- Hoof trimming: Every 6 months', 'general', 'dairy', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(19, 'Profitable Goat Farming', '**Goat Production Guide:**\n\r\n**Popular Breeds:**\n\r\n\n\r\n- **Boer:** Meat, fast growth (50kg in 12 months)\n\r\n- **Saanen:** Dairy, 2-3 liters milk/day\n\r\n- **Toggenburg:** Dairy, hardy\n\r\n- **Small East African:** Local, adapted\n\r\n- **Crossbreeds:** Improved productivity\n\r\n\n\r\n**Starting Investment (10 does + 1 buck):**\n\r\n\n\r\n- Goats: UGX 3-5 million\n\r\n- Housing: UGX 1-2 million\n\r\n- Equipment: UGX 300,000\n\r\n- Total: UGX 4.3-7.3 million\n\r\n\n\r\n**Management Practices:**\n\r\n\n\r\n- **Housing:** Raised floor, good ventilation\n\r\n- **Space:** 1.5 sq meters per adult goat\n\r\n- **Feeding:** Napier grass, browse, concentrates\n\r\n- **Water:** Clean water always available\n\r\n- **Breeding:** Kids at 7-8 months age\n\r\n\n\r\n**Productivity:**\n\r\n\n\r\n- **Kidding interval:** 8-9 months\n\r\n- **Kids per birth:** 1-3 (usually 2)\n\r\n- **Kids per year:** 3-4 kids per doe\n\r\n- **Market weight:** 25-30kg at 6-8 months\n\r\n- **Price:** UGX 150,000-300,000 per goat\n\r\n\n\r\n**Annual Income (10 does):**\n\r\n\n\r\n- Kids produced: 30-35 per year\n\r\n- Mortality: 15% = 25-30 kids survive\n\r\n- Revenue: 25 × UGX 200,000 = UGX 5 million\n\r\n- Operating costs: UGX 1.5 million\n\r\n- **Net profit: UGX 3.5 million per year**\n\r\n\n\r\n**Health Management:**\n\r\n\n\r\n- Deworming: Every 3 months\n\r\n- Vaccination: PPR, Anthrax, Goat Pox\n\r\n- Hoof trimming: Every 2-3 months\n\r\n- External parasite control: Weekly spraying', 'general', 'livestock', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41'),
(20, 'Pig Farming for Beginners', '**Commercial Pig Production:**\n\r\n**Popular Breeds:**\n\r\n\n\r\n- **Large White:** Fast growth, large litters\n\r\n- **Landrace:** Long body, good meat\n\r\n- **Duroc:** Hardy, good mothering\n\r\n- **Camborough:** Hybrid, very productive\n\r\n\n\r\n**Starting Investment (5 sows + 1 boar):**\n\r\n\n\r\n- Breeding stock: UGX 4-6 million\n\r\n- Housing: UGX 3-5 million\n\r\n- Equipment: UGX 500,000\n\r\n- Initial feed: UGX 500,000\n\r\n- Total: UGX 8-12 million\n\r\n\n\r\n**Housing Requirements:**\n\r\n\n\r\n- Space per sow: 4-5 sq meters\n\r\n- Farrowing pen: 6-8 sq meters\n\r\n- Solid concrete floor\n\r\n- Good drainage essential\n\r\n- Separate weaners, growers, breeders\n\r\n\n\r\n**Feeding Program:**\n\r\n**Pregnant Sow:**\n\n\r\n\n\r\n- 2.5-3kg per day\n\r\n- 16% protein concentrate\n\r\n\n\r\n**Lactating Sow:**\n\n\r\n\n\r\n- 5-7kg per day\n\r\n- 18% protein concentrate\n\r\n\n\r\n**Growers (20-100kg):**\n\n\r\n\n\r\n- 1.5-3kg per day\n\r\n- 16-18% protein\n\r\n- FCR: 3:1 (3kg feed for 1kg gain)\n\r\n\n\r\n**Production Cycle:**\n\r\n\n\r\n- **Gestation:** 114 days (3 months, 3 weeks, 3 days)\n\r\n- **Lactation:** 28 days (4 weeks)\n\r\n- **Weaning to service:** 7 days\n\r\n- **Total cycle:** 149 days (~5 months)\n\r\n- **Litters per year:** 2.4\n\r\n\n\r\n**Productivity Targets:**\n\r\n\n\r\n- Litter size: 10-12 piglets\n\r\n- Weaning survival: 90% = 9-11 piglets\n\r\n- Grower survival: 95%\n\r\n- Market weight: 90-100kg at 6 months\n\r\n\n\r\n**Annual Income (5 sows):**\n\r\n**Production:**\n\n\r\n\n\r\n- Total piglets: 5 sows × 2.4 litters × 10 = 120 piglets/year\n\r\n- Weaned: 108 piglets\n\r\n- Market ready: 103 pigs\n\r\n\n\r\n**Revenue:**\n\n\r\n\n\r\n- 103 pigs × 90kg × UGX 7,000/kg = UGX 64,890,000\n\r\n\n\r\n**Costs:**\n\n\r\n\n\r\n- Feed: UGX 35 million\n\r\n- Veterinary: UGX 2 million\n\r\n- Labor: UGX 3.6 million\n\r\n- Utilities: UGX 1 million\n\r\n- Total: UGX 41.6 million\n\r\n\n\r\n**Net profit: UGX 23 million per year**\n\n\r\n**Disease Prevention:**\n\r\n\n\r\n- Vaccination: Classical Swine Fever, FMD\n\r\n- Biosecurity: Critical - pigs very disease susceptible\n\r\n- Deworming: Every 3-4 months\n\r\n- Castration: Males at 2-3 weeks', 'general', 'piggery', 'all_year', 'en', NULL, NULL, 1, '2026-02-03 09:48:32', '2026-02-03 11:00:41');

-- --------------------------------------------------------

--
-- Table structure for table `ai_conversations`
--

CREATE TABLE `ai_conversations` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `session_id` varchar(100) DEFAULT NULL,
  `message` text NOT NULL,
  `response` text NOT NULL,
  `context_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`context_data`)),
  `language` varchar(10) DEFAULT 'en',
  `source` enum('openai','rule_based','error') NOT NULL DEFAULT 'rule_based',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `ai_conversations`
--

INSERT INTO `ai_conversations` (`id`, `user_id`, `session_id`, `message`, `response`, `context_data`, `language`, `source`, `created_at`) VALUES
(1, 3, 'ai_session_69808f06a7af99.96345284', 'helo', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 11:48:22'),
(2, 3, 'ai_session_69808f06a7af99.96345284', 'when is right to plant cassava', '**🌿 Cassava Planting Guide**\n\n**Best Planting Time:**\n- **Start of rainy season** (March-April or Sept-Oct)\n- Soil should be moist but not waterlogged\n- Cassava needs 8-12 months, so time your harvest\n\n**Planting Procedure:**\n\n**1. Prepare Cuttings:**\n- Use healthy 8-12 month old plants\n- Cut stems into 25-30cm pieces\n- Use middle portions (better than top/bottom)\n- Each cutting should have 5-7 nodes\n- Plant within 24 hours of cutting\n\n**2. Land Preparation:**\n- Clear land completely\n- Make mounds or ridges (optional but better)\n- Add manure if available (5 tons/acre)\n\n**3. Spacing:**\n- **1 meter x 1 meter** (standard)\n- Gives 4,000 plants per acre\n- Closer spacing (0.8m x 0.8m) for earlier harvest\n\n**4. Planting Method:**\n- Plant cuttings at 45° angle or flat\n- Bury 2/3 of cutting in soil\n- Leave 1/3 (2-3 nodes) above ground\n- Firm soil around cutting\n\n**Cutting Requirements:**\n- 4,000-6,000 cuttings per acre\n- Get from reliable source or own healthy field\n- Cost: UGX 50-100 per cutting\n\n**Top Varieties:**\n\n**High Yielding:**\n- **NASE 14** - 35-40 tons/acre, resistant to CBSD\n- **NASE 19** - 30-35 tons/acre\n- **NASE 3** - Early maturing\n\n**Disease Resistant:**\n- **TME 14** - CMD resistant\n- **Mkumba** - CBSD resistant\n- **NASE 18** - Multiple disease resistance\n\n**Management:**\n- **1st weeding:** 1 month after planting\n- **2nd weeding:** 3 months\n- **3rd weeding:** 5 months (if needed)\n- No fertilizer usually needed\n- Check regularly for diseases\n\n**Harvest:**\n- **10-12 months:** Food cassava\n- **12-18 months:** Industrial cassava\n- Don\'t delay >18 months (roots become woody)\n- Harvest during dry season\n\n**Yield Expectation:**\n- Good management: 25-40 tons/acre\n- Average: 15-20 tons/acre\n- Poor management: <10 tons/acre\n\n💡 **Pro Tip:** Intercrop with beans in first 3-4 months for extra income!\n\n*This applies to the Luuka region*', NULL, 'en', 'rule_based', '2026-02-02 11:48:56'),
(3, 3, 'ai_session_69808f06a7af99.96345284', 'What are the signs of maize rust disease?', '**🌽 Maize Rust Disease Control**\n\n**Symptoms to Watch For:**\n- Small circular to elongated brown pustules on leaves\n- Rust appears on both sides of leaves\n- Yellow to orange rust spores when rubbed\n- Severe cases: leaves dry prematurely\n\n**Control Methods:**\n\n**1. Chemical Control:**\n- Spray **Mancozeb** or **Metalaxyl** fungicide\n- Apply when first symptoms appear\n- Repeat every 14 days if needed\n- Cost: UGX 15,000-25,000 per kg\n\n**2. Resistant Varieties (Best Solution):**\n- **Longe 10H** - Excellent resistance\n- **DH04** - Good resistance, high yield\n- **Longe 5** - Tolerant variety\n- **NASE varieties** - Local resistant types\n\n**3. Cultural Practices:**\n- Rotate with legumes (beans, groundnuts)\n- Remove infected crop residues after harvest\n- Plant with proper spacing (75cm x 30cm)\n- Apply balanced NPK fertilizer\n\n**4. Prevention:**\n- Use certified, disease-free seeds\n- Plant during recommended season\n- Avoid overhead irrigation\n- Keep field weed-free\n\n💡 **Pro Tip:** Early planting (start of rains) helps avoid rust!\n\n*This applies to the Luuka region*', NULL, 'en', 'rule_based', '2026-02-02 11:50:05'),
(4, 3, 'ai_session_69808f06a7af99.96345284', 'When is the best time to plant beans?', '**🫘 Bean Planting Guide for Uganda**\n\n**Best Planting Times:**\n\n**Season 1:**\n- **February - March**\n- Main season, higher yields\n- Harvest: May - June\n\n**Season 2:**\n- **August - September**\n- Short season\n- Harvest: November - December\n\n**Requirements:**\n- Rainfall: Minimum 300mm\n- Temperature: 18-24°C optimal\n- Well-drained soil, pH 6.0-7.5\n- Avoid waterlogged areas\n\n**Planting Instructions:**\n\n**Spacing:**\n- Between rows: **50cm**\n- Within row: **10cm**\n- Depth: **3-5cm**\n- 1-2 seeds per hole\n\n**Seed Rate:**\n- 40-50kg per acre\n- Cost: UGX 50,000-80,000\n\n**Fertilizer:**\n- **DAP:** 50kg/acre at planting\n- Beans fix nitrogen, need less fertilizer\n- Top dress if soil poor\n\n**Top Varieties:**\n\n**Climbing Beans:**\n- **NABE 15** - 90 days, 2.5 tons/acre\n- **NABE 16** - 90 days, good market\n- **NABE 17** - 85 days, drought tolerant\n\n**Bush Beans:**\n- **K132** - 75 days, disease resistant\n- **K131** - 80 days\n- **NABE 4** - 75 days, good yield\n\n**Management:**\n- Weed 2-3 times\n- Stake climbing beans at 2 weeks\n- Watch for aphids and bean fly\n- Spray if needed\n\n**Harvest:**\n- When 90% pods are dry\n- Sun-dry to 13% moisture\n- Store in cool, dry place\n\n💡 **Intercrop with maize** for better land use!', NULL, 'en', 'rule_based', '2026-02-02 11:50:07'),
(5, 3, 'ai_session_69808f06a7af99.96345284', '🌱 Best time to plant maize', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 11:54:58'),
(6, 3, 'ai_session_69808f06a7af99.96345284', 'when to plant beans', '**🫘 Bean Planting Guide for Uganda**\n\n**Best Planting Times:**\n\n**Season 1:**\n- **February - March**\n- Main season, higher yields\n- Harvest: May - June\n\n**Season 2:**\n- **August - September**\n- Short season\n- Harvest: November - December\n\n**Requirements:**\n- Rainfall: Minimum 300mm\n- Temperature: 18-24°C optimal\n- Well-drained soil, pH 6.0-7.5\n- Avoid waterlogged areas\n\n**Planting Instructions:**\n\n**Spacing:**\n- Between rows: **50cm**\n- Within row: **10cm**\n- Depth: **3-5cm**\n- 1-2 seeds per hole\n\n**Seed Rate:**\n- 40-50kg per acre\n- Cost: UGX 50,000-80,000\n\n**Fertilizer:**\n- **DAP:** 50kg/acre at planting\n- Beans fix nitrogen, need less fertilizer\n- Top dress if soil poor\n\n**Top Varieties:**\n\n**Climbing Beans:**\n- **NABE 15** - 90 days, 2.5 tons/acre\n- **NABE 16** - 90 days, good market\n- **NABE 17** - 85 days, drought tolerant\n\n**Bush Beans:**\n- **K132** - 75 days, disease resistant\n- **K131** - 80 days\n- **NABE 4** - 75 days, good yield\n\n**Management:**\n- Weed 2-3 times\n- Stake climbing beans at 2 weeks\n- Watch for aphids and bean fly\n- Spray if needed\n\n**Harvest:**\n- When 90% pods are dry\n- Sun-dry to 13% moisture\n- Store in cool, dry place\n\n💡 **Intercrop with maize** for better land use!', NULL, 'en', 'rule_based', '2026-02-02 11:55:35'),
(7, 3, 'ai_session_69808f06a7af99.96345284', 'can i grow rice in uganda', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 11:58:21'),
(8, 3, 'ai_session_69808f06a7af99.96345284', 'what is the price for beans now', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 11:59:04'),
(9, 3, 'ai_session_69808f06a7af99.96345284', 'Fertilizer recommendations', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 11:59:23'),
(10, 3, 'ai_session_69808f06a7af99.96345284', 'price for beans', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 12:00:09'),
(11, 3, 'ai_session_69808f06a7af99.96345284', 'Ndisima ditya okuzuukusa ettaka?', '**🌾 Okuzuukusa Ettaka n\'Okuteekamu Fertilizer**\n\n**Engeri z\'Obuwangwa:**\n\n**1. Compost:**\n- Tabaganya: ebisigadde by\'ebirime + obusa + ebiva mu ffumbiro\n- Teekawo layer brown (bikalu) ne green (biggya)\n- Leka ebinyogovu, kyusa buli wiiki\n- Vaamu mu myezi 2-3\n- Teekamu: 5-10 tonnes buli acre\n\n**2. Obusa bw\'ebisolo:**\n- **Ente/Embuzi:** 10 tonnes/acre\n- **Enkoko:** 3-5 tonnes/acre (nitrogen nnyingi)\n- **Embizzi:** 8 tonnes/acre\n- Teekamu wiiki 2-3 nga tonnasimba\n\n**3. Green Manure (Ebirime by\'okuzuukusa):**\n- Simba ebinyeebwa: bikooge, peas, mucuna\n- Bifuna nitrogen okuva mu mpola\n- Bimeewo mu ttaka nga tebinnamera\n\n**4. Mulching:**\n- Kozesa omuddo, ebikoola, ebisigadde by\'ebirime\n- Bikuuma obunnyogovu, biteekamu organic matter\n- Teekamu layer ya 5-10cm\n\n**Fertilizer ezikoleddwa:**\n\n**1. DAP (Diammonium Phosphate):**\n- **Ddi:** Wakati w\'okusimba\n- **Omuwendo:** 50kg/acre\n- **Nutrients:** Phosphorus nnyingi (18-46-0)\n- **Esingako:** Emirandira, okumula\n\n**2. Urea:**\n- **Ddi:** Top dressing, wiiki 4-6 oluvannyuma lw\'okusimba\n- **Omuwendo:** 50kg/acre\n- **Nutrients:** Nitrogen nnyingi (46-0-0)\n- **Esingako:** Okukula kw\'ebikoola, langi ya green\n\n**3. NPK (17:17:17):**\n- **Ddi:** Wakati w\'okusimba oba okugabanya\n- **Omuwendo:** 100kg/acre\n- **Nutrients:** Balanced\n- **Esingako:** Okukula okwa bulijjo\n\n**4. CAN (Calcium Ammonium Nitrate):**\n- **Omuwendo:** 50kg/acre\n- **Nutrients:** Nitrogen + Calcium\n- **Esingako:** Top dressing\n\n**Okugezesa Ettaka:**\n- Genda ku NARL Kawanda oba district agricultural office\n- Emiwendo: UGX 20,000-50,000\n- Funa amagezi agalagiddwa\n\n**Engeri y\'okuteekamu:**\n- Teeka fertilizer 5cm okuva ku kirime\n- Bikke n\'ettaka oluvannyuma lw\'okuteeka\n- Teeka nga ettaka liriko obunnyogovu\n- Toteeka ng\'enkuba ekube nnyo\n\n💡 **Tabaganya engeri z\'obuwangwa n\'ezikoleddwa** okufuna ebisingako!\n\n*Ebyo bigwanidde Luuka*', NULL, 'lusoga', 'rule_based', '2026-02-02 12:00:24'),
(12, 3, 'ai_session_69808f06a7af99.96345284', 'What are the signs of maize rust disease?', '**🌽 Maize Rust Disease Control**\n\n**Symptoms to Watch For:**\n- Small circular to elongated brown pustules on leaves\n- Rust appears on both sides of leaves\n- Yellow to orange rust spores when rubbed\n- Severe cases: leaves dry prematurely\n\n**Control Methods:**\n\n**1. Chemical Control:**\n- Spray **Mancozeb** or **Metalaxyl** fungicide\n- Apply when first symptoms appear\n- Repeat every 14 days if needed\n- Cost: UGX 15,000-25,000 per kg\n\n**2. Resistant Varieties (Best Solution):**\n- **Longe 10H** - Excellent resistance\n- **DH04** - Good resistance, high yield\n- **Longe 5** - Tolerant variety\n- **NASE varieties** - Local resistant types\n\n**3. Cultural Practices:**\n- Rotate with legumes (beans, groundnuts)\n- Remove infected crop residues after harvest\n- Plant with proper spacing (75cm x 30cm)\n- Apply balanced NPK fertilizer\n\n**4. Prevention:**\n- Use certified, disease-free seeds\n- Plant during recommended season\n- Avoid overhead irrigation\n- Keep field weed-free\n\n💡 **Pro Tip:** Early planting (start of rains) helps avoid rust!\n\n*This applies to the Luuka region*', NULL, 'en', 'rule_based', '2026-02-02 12:01:03'),
(13, 3, 'ai_session_69811701ed2432.78100543', 'hi', 'Hello! 👋 Great to hear from you!\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. I\'m here to help you succeed in farming!\n\n**I can help you with:**\n🌱 **Crop Diseases & Pests** - Identify and treat problems\n📅 **Planting Schedules** - Know when to plant for best yields\n💰 **Market Prices** - Get current prices and selling tips\n🌾 **Best Practices** - Learn modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats management\n☀️ **Weather Advice** - Climate-smart farming tips\n\n**You can ask in English or Lusoga!**\nWhat would you like to know? 🚜', NULL, 'en', 'rule_based', '2026-02-02 21:28:33'),
(14, 3, 'ai_session_69811701ed2432.78100543', 'common diseases for maize', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 21:29:35'),
(15, 3, 'ai_session_69811701ed2432.78100543', 'Best time to plant maize', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 21:40:03'),
(16, 3, 'ai_session_69811701ed2432.78100543', 'Fertilizer tips', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 21:40:23'),
(17, 3, 'ai_session_69811701ed2432.78100543', 'Current market prices', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 21:41:21'),
(18, 3, 'ai_session_69811701ed2432.78100543', 'planting maize', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-02 21:41:50'),
(19, 3, 'ai_session_69819d82c849a0.63659128', 'when to plant beans', '**🫘 Bean Planting Guide for Uganda**\n\n**Best Planting Times:**\n\n**Season 1:**\n- **February - March**\n- Main season, higher yields\n- Harvest: May - June\n\n**Season 2:**\n- **August - September**\n- Short season\n- Harvest: November - December\n\n**Requirements:**\n- Rainfall: Minimum 300mm\n- Temperature: 18-24°C optimal\n- Well-drained soil, pH 6.0-7.5\n- Avoid waterlogged areas\n\n**Planting Instructions:**\n\n**Spacing:**\n- Between rows: **50cm**\n- Within row: **10cm**\n- Depth: **3-5cm**\n- 1-2 seeds per hole\n\n**Seed Rate:**\n- 40-50kg per acre\n- Cost: UGX 50,000-80,000\n\n**Fertilizer:**\n- **DAP:** 50kg/acre at planting\n- Beans fix nitrogen, need less fertilizer\n- Top dress if soil poor\n\n**Top Varieties:**\n\n**Climbing Beans:**\n- **NABE 15** - 90 days, 2.5 tons/acre\n- **NABE 16** - 90 days, good market\n- **NABE 17** - 85 days, drought tolerant\n\n**Bush Beans:**\n- **K132** - 75 days, disease resistant\n- **K131** - 80 days\n- **NABE 4** - 75 days, good yield\n\n**Management:**\n- Weed 2-3 times\n- Stake climbing beans at 2 weeks\n- Watch for aphids and bean fly\n- Spray if needed\n\n**Harvest:**\n- When 90% pods are dry\n- Sun-dry to 13% moisture\n- Store in cool, dry place\n\n💡 **Intercrop with maize** for better land use!', NULL, 'en', 'rule_based', '2026-02-03 07:02:26'),
(20, 3, 'session_3_1770103487_7f47e87c4373b94e', 'hello', 'Hello! 👋 Great to hear from you!\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. I\'m here to help you succeed in farming!\n\n**I can help you with:**\n🌱 **Crop Diseases & Pests** - Identify and treat problems\n📅 **Planting Schedules** - Know when to plant for best yields\n💰 **Market Prices** - Get current prices and selling tips\n🌾 **Best Practices** - Learn modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats management\n☀️ **Weather Advice** - Climate-smart farming tips\n\n**You can ask in English or Lusoga!**\nWhat would you like to know? 🚜', NULL, 'en', 'rule_based', '2026-02-03 07:24:51'),
(21, 3, 'session_3_1770112685_fe7c612730000e52', 'tomato diseases', '**🍅 Tomato Farming Complete Guide**\n\n**Why Grow Tomatoes?**\n- High demand all year\n- Good profit margins\n- Quick returns (3-4 months)\n- Multiple harvests possible\n- Can be grown in small spaces\n\n**Best Varieties for Uganda:**\n\n**Open Pollinated (Can Save Seeds):**\n- **Money Maker** - Large fruits, disease resistant\n- **Roma VF** - Processing type, firm\n- **Cal-J** - High yielding, heat tolerant\n- **MT56** - Disease resistant, good for local markets\n\n**Hybrid (Higher yields, can\'t save seeds):**\n- **Anna F1** - Very high yield, disease resistant\n- **Kilele F1** - Heat tolerant, long shelf life\n- **Eden F1** - Uniform fruits, market preferred\n- **Rambo F1** - Determinate, early maturing\n\n**Planting Guide:**\n\n**Nursery Stage (4-6 weeks):**\n\n**Seed Rate:**\n- 200-300g seeds per acre\n- Yields 30,000-40,000 seedlings\n- Cost: UGX 50,000 - 200,000 (hybrids expensive)\n\n**Nursery Preparation:**\n1. Mix topsoil : manure : sand (3:2:1)\n2. Fill seed trays or small pots\n3. Plant seeds 0.5cm deep\n4. Water gently daily\n5. Cover with plastic sheet first 3 days\n6. Shade for 2 weeks, then expose to sun\n\n**Transplanting (after 4-6 weeks):**\n- Seedling height: 10-15cm\n- 4-6 true leaves\n- Transplant evening or cloudy day\n\n**Field Preparation:**\n\n**Land Preparation:**\n- Deep plowing (20-25cm)\n- Add well-rotted manure: 10-15 tons/acre\n- Make ridges or raised beds\n- Install drip irrigation if possible\n\n**Spacing:**\n- Between rows: **90-100cm**\n- Within row: **45-60cm**\n- Population: 12,000-15,000 plants/acre\n\n**Fertilizer Application:**\n\n**At Planting:**\n- **DAP:** 150kg/acre OR\n- **NPK (17:17:17):** 200kg/acre\n- Mix with soil in planting hole\n\n**Top Dressing:**\n- **Week 3:** CAN 100kg/acre\n- **Week 6:** CAN 100kg/acre\n- **Week 9:** NPK 50kg/acre\n\n**Or use foliar fertilizers:**\n- **Optimizer/Lavender/Omex** weekly sprays\n\n**Staking & Training:**\n- Install stakes 1 week after transplanting\n- Use wooden poles, strings, or wires\n- Tie plants weekly as they grow\n- Remove side shoots (suckers) weekly\n- Train to single or double stem\n\n**Irrigation:**\n- Critical first 2 weeks after transplanting\n- Water deeply 2-3 times per week\n- Drip irrigation ideal (saves 50% water)\n- Avoid overhead watering (spreads disease)\n- Mulch to conserve moisture\n\n**Weed Management:**\n- First weeding: 2 weeks after transplanting\n- Subsequent weeding: Every 2-3 weeks\n- Use mulch to suppress weeds\n- Shallow cultivation to avoid root damage\n\n**Common Diseases & Control:**\n\n**1. Early Blight**\n- Symptoms: Brown spots with rings on lower leaves\n- Control: **Mancozeb** or **Copper oxychloride**\n- Spray every 7-10 days\n\n**2. Late Blight**\n- Symptoms: Dark brown lesions, white fuzzy growth\n- Control: **Ridomil Gold** or **Dithane M45**\n- Very destructive, spray preventively\n\n**3. Bacterial Wilt**\n- Symptoms: Sudden wilting, no yellowing\n- Control: No cure! Remove infected plants\n- Crop rotation, resistant varieties\n\n**4. Fusarium Wilt**\n- Symptoms: Yellowing one side of plant\n- Control: Use resistant varieties (V, F labels)\n- Soil fumigation\n\n**5. Tomato Leaf Miner**\n- Symptoms: Winding tunnels in leaves\n- Control: **Radiant**, **Delegate**, or **Belt**\n- Spray weekly during pest season\n\n**6. Whiteflies**\n- Transmit viruses\n- Control: **Confidor**, **Actellic**, yellow sticky traps\n\n**Pest & Disease Spray Program:**\n\n**Week 1-2:** Establish plants\n**Week 3:** Fungicide (Mancozeb) + Foliar feed\n**Week 4:** Insecticide (Dimethoate) + Foliar\n**Week 5:** Fungicide + Foliar\n**Week 6:** Insecticide for leaf miner + Foliar\n**Week 7 onwards:** Alternate fungicide/insecticide weekly\n\n**Harvesting:**\n- First harvest: 10-12 weeks after transplanting\n- Harvest when fruits turn pink/red\n- Pick every 2-3 days\n- Productive period: 3-4 months\n- Handle carefully to avoid bruising\n\n**Yield Expectations:**\n- **Hybrids:** 30-50 tons/acre\n- **Open pollinated:** 15-25 tons/acre\n- **Organic farming:** 10-20 tons/acre\n\n**Economic Analysis (1 Acre, Hybrid):**\n\n**Costs:**\n- Seeds (hybrid): UGX 150,000\n- Fertilizers: UGX 800,000\n- Pesticides: UGX 500,000\n- Stakes/strings: UGX 400,000\n- Labor: UGX 1,000,000\n- Irrigation: UGX 300,000\n- Transport: UGX 200,000\n- **Total: UGX 3,350,000**\n\n**Revenue:**\n- Yield: 35 tons (conservative)\n- Price: UGX 1,500 - 3,500 per kg (season dependent)\n- **Gross income: UGX 52,500,000 - 122,500,000**\n\n**Net Profit:**\n- Low season: UGX 49,150,000\n- High season: UGX 119,150,000\n- **Average: UGX 80 - 90 million per acre!**\n\n**Marketing:**\n- Pre-arrange buyers (hotels, restaurants, supermarkets)\n- Join farmer groups for collective marketing\n- Consider value addition (tomato paste, juice)\n- Use AIMS marketplace\n- Best prices: December-March (dry season)\n- Lowest prices: April-June (peak harvest)\n\n💡 **Success Tips:**\n- Choose disease-resistant varieties\n- Don\'t compromise on quality inputs\n- Strict spray program\n- Proper staking and training\n- Good market research before planting\n- Start small (0.25 acre) to learn\n- Keep detailed records', NULL, 'en', 'rule_based', '2026-02-03 09:58:07'),
(22, 3, 'session_3_1770112685_fe7c612730000e52', 'poultry diseases', '**Preventing Poultry Diseases**\n\n<h5>Biosecurity and Disease Prevention:</h5>\r\n<h6>Critical Biosecurity Measures:</h6>\r\n<ol>\r\n<li><strong>Footbaths:</strong> Disinfectant at all entry points</li>\r\n<li><strong>All-in, All-out:</strong> Never mix age groups</li>\r\n<li><strong>Quarantine:</strong> Isolate new birds for 2 weeks</li>\r\n<li><strong>Vaccination:</strong> Follow strict schedule</li>\r\n<li><strong>Cleanliness:</strong> Daily water change, weekly litter management</li>\r\n</ol>\r\n<h6>Essential Vaccines:</h6>\r\n<ul>\r\n<li>Newcastle Disease: Most important! Vaccinate regularly</li>\r\n<li>Gumboro: Protects immune system</li>\r\n<li>Infectious Bronchitis: Prevents respiratory issues</li>\r\n<li>Fowl Pox: Especially in wet seasons</li>\r\n<li>Mareks: At day old</li>\r\n</ul>\r\n<p><strong>Cost of prevention:</strong> UGX 200-300 per bird</p>\r\n<p><strong>Cost of disease outbreak:</strong> 50-100% mortality!</p>\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 10:22:45'),
(23, 3, 'session_3_1770112685_fe7c612730000e52', 'poultry diseases', '**Preventing Poultry Diseases**\n\n**Biosecurity and Disease Prevention:**\n\r\n**Critical Biosecurity Measures:**\n\r\n\n\r\n- **Footbaths:** Disinfectant at all entry points\n\r\n- **All-in, All-out:** Never mix age groups\n\r\n- **Quarantine:** Isolate new birds for 2 weeks\n\r\n- **Vaccination:** Follow strict schedule\n\r\n- **Cleanliness:** Daily water change, weekly litter management\n\r\n\n\r\n**Essential Vaccines:**\n\r\n\n\r\n- Newcastle Disease: Most important! Vaccinate regularly\n\r\n- Gumboro: Protects immune system\n\r\n- Infectious Bronchitis: Prevents respiratory issues\n\r\n- Fowl Pox: Especially in wet seasons\n\r\n- Mareks: At day old\n\r\n\n\r\n**Cost of prevention:** UGX 200-300 per bird\n\n\r\n**Cost of disease outbreak:** 50-100% mortality!\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 11:01:17'),
(24, 3, 'session_3_1770129862_bbe17faa921e5c85', 'Tomato growing', '**Tomato Farming for Profit**\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 14:44:22'),
(25, 3, 'session_3_1770129862_bbe17faa921e5c85', 'poultry keeping', '**Preventing Poultry Diseases**\n\n**Biosecurity and Disease Prevention:**\n\r\n**Critical Biosecurity Measures:**\n\r\n\n\r\n- **Footbaths:** Disinfectant at all entry points\n\r\n- **All-in, All-out:** Never mix age groups\n\r\n- **Quarantine:** Isolate new birds for 2 weeks\n\r\n- **Vaccination:** Follow strict schedule\n\r\n- **Cleanliness:** Daily water change, weekly litter management\n\r\n\n\r\n**Essential Vaccines:**\n\r\n\n\r\n- Newcastle Disease: Most important! Vaccinate regularly\n\r\n- Gumboro: Protects immune system\n\r\n- Infectious Bronchitis: Prevents respiratory issues\n\r\n- Fowl Pox: Especially in wet seasons\n\r\n- Mareks: At day old\n\r\n\n\r\n**Cost of prevention:** UGX 200-300 per bird\n\n\r\n**Cost of disease outbreak:** 50-100% mortality!\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 14:45:01'),
(26, 3, 'session_3_1770129862_bbe17faa921e5c85', 'cassava diseases', '**Preventing Poultry Diseases**\n\n**Biosecurity and Disease Prevention:**\n\r\n**Critical Biosecurity Measures:**\n\r\n\n\r\n- **Footbaths:** Disinfectant at all entry points\n\r\n- **All-in, All-out:** Never mix age groups\n\r\n- **Quarantine:** Isolate new birds for 2 weeks\n\r\n- **Vaccination:** Follow strict schedule\n\r\n- **Cleanliness:** Daily water change, weekly litter management\n\r\n\n\r\n**Essential Vaccines:**\n\r\n\n\r\n- Newcastle Disease: Most important! Vaccinate regularly\n\r\n- Gumboro: Protects immune system\n\r\n- Infectious Bronchitis: Prevents respiratory issues\n\r\n- Fowl Pox: Especially in wet seasons\n\r\n- Mareks: At day old\n\r\n\n\r\n**Cost of prevention:** UGX 200-300 per bird\n\n\r\n**Cost of disease outbreak:** 50-100% mortality!\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 14:45:41'),
(27, 3, 'session_3_1770129986_18eb88d8acaa1008', 'cassava growing', '**Profitable Cabbage Production**\n\n**Growing Quality Cabbage:**\n\r\n**Best Varieties:**\n\r\n\n\r\n- **Gloria F1:** Large heads (2-3kg), disease resistant\n\r\n- **Blue Dynasty:** Very large (3-5kg), heat tolerant\n\r\n- **Copenhagen Market:** Good for processing\n\r\n\n\r\n**Planting Guide:**\n\r\n\n\r\n- Spacing: 60cm x 45cm (24,000 plants/acre)\n\r\n- Fertilizer: Base - 200kg DAP, Top - 150kg CAN (split)\n\r\n- Maturity: 90-120 days\n\r\n- Irrigation: Critical in dry months\n\r\n\n\r\n**Pest & Disease Management:**\n\r\n\n\r\n- **Diamond Back Moth:** Belt, Radiant weekly\n\r\n- **Aphids:** Confidor, neem oil\n\r\n- **Black Rot:** Copper-based fungicides\n\r\n- **Clubroot:** Lime soil, rotate crops\n\r\n\n\r\n**Marketing:**\n\r\nPrice: UGX 1,000-3,000 per head depending on season. Highest prices December-February.\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 14:46:27'),
(28, 3, 'session_3_1770130170_b7f72fe9ee72611e', 'what are the tomato diseases', '**Preventing Poultry Diseases**\n\n**Biosecurity and Disease Prevention:**\n\r\n**Critical Biosecurity Measures:**\n\r\n\n\r\n- **Footbaths:** Disinfectant at all entry points\n\r\n- **All-in, All-out:** Never mix age groups\n\r\n- **Quarantine:** Isolate new birds for 2 weeks\n\r\n- **Vaccination:** Follow strict schedule\n\r\n- **Cleanliness:** Daily water change, weekly litter management\n\r\n\n\r\n**Essential Vaccines:**\n\r\n\n\r\n- Newcastle Disease: Most important! Vaccinate regularly\n\r\n- Gumboro: Protects immune system\n\r\n- Infectious Bronchitis: Prevents respiratory issues\n\r\n- Fowl Pox: Especially in wet seasons\n\r\n- Mareks: At day old\n\r\n\n\r\n**Cost of prevention:** UGX 200-300 per bird\n\n\r\n**Cost of disease outbreak:** 50-100% mortality!\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-03 14:49:30'),
(29, 3, 'session_3_1770266734_b7d55e199ae706b5', 'what are the tomato diseases', '**Tomato Farming for Profit**\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 04:45:34'),
(30, 3, 'session_3_1770266734_b7d55e199ae706b5', 'diseases affecting tomatoes', '**Tomato Farming for Profit**\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 04:46:28'),
(31, 3, 'session_3_1770272999_af2a7dc8bcff46fd', 'Best time to plant maize', '**🦠 Maize Streak Virus**\n*Maize streak virus (MSV)*\n\n**Crop:** Maize\n**Severity:** High\n\n**Symptoms:**\nYellow streaks along leaf veins, stunted growth, reduced yield\n\n**Treatment:**\nNo cure available - focus on prevention, remove infected plants\n\n**Prevention:**\nPlant resistant varieties, control leafhopper population, remove infected plants early\n', NULL, 'en', '', '2026-02-05 06:29:59'),
(32, 3, 'session_3_1770272999_af2a7dc8bcff46fd', 'maize diseases', '**🦠 Maize Streak Virus**\n*Maize streak virus (MSV)*\n\n**Crop:** Maize\n**Severity:** High\n\n**Symptoms:**\nYellow streaks along leaf veins, stunted growth, reduced yield\n\n**Treatment:**\nNo cure available - focus on prevention, remove infected plants\n\n**Prevention:**\nPlant resistant varieties, control leafhopper population, remove infected plants early\n', NULL, 'en', '', '2026-02-05 06:30:27'),
(33, 3, 'session_3_1770291314_f73fd51f347d8a9d', 'hello', 'Good afternoon! 👋\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. Great to connect with you!\n\n**I can help you with:**\n🌱 **Crop Diseases** - Identify and treat problems\n📅 **Planting Schedules** - Best times to plant\n💰 **Market Prices** - Current prices and trends\n🌾 **Best Practices** - Modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats\n\nWhat would you like to know today? 😊', NULL, 'en', '', '2026-02-05 11:35:14'),
(34, 3, 'session_3_1770291314_f73fd51f347d8a9d', 'tomato diseases', '**Tomato Farming for Profit**\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 11:35:40'),
(35, 3, 'session_3_1770291398_5665901072123512', 'hi', 'Hello! 👋 Great to hear from you!\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. I\'m here to help you succeed in farming!\n\n**I can help you with:**\n🌱 **Crop Diseases & Pests** - Identify and treat problems\n📅 **Planting Schedules** - Know when to plant for best yields\n💰 **Market Prices** - Get current prices and selling tips\n🌾 **Best Practices** - Learn modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats management\n☀️ **Weather Advice** - Climate-smart farming tips\n\n**You can ask in English or Lusoga!**\nWhat would you like to know? 🚜', NULL, 'en', 'rule_based', '2026-02-05 11:36:42'),
(36, 3, 'session_3_1770291398_5665901072123512', 'tomoto diseases', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests**\n- **Planting Schedules**\n- **Market Prices**\n- **Soil Management**\n- **Weather & Climate**\n- **Livestock Care**\n\nPlease ask a specific question about farming! 🌾', NULL, 'en', 'rule_based', '2026-02-05 11:37:11'),
(37, 3, 'session_3_1770291398_5665901072123512', 'tomato growing', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests**\n- **Planting Schedules**\n- **Market Prices**\n- **Soil Management**\n- **Weather & Climate**\n- **Livestock Care**\n\nPlease ask a specific question about farming! 🌾', NULL, 'en', 'rule_based', '2026-02-05 11:37:46'),
(38, 3, 'ai_session_698481468883a5.38727573', 'hello', 'Hello! 👋 Great to hear from you!\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. I\'m here to help you succeed in farming!\n\n**I can help you with:**\n🌱 **Crop Diseases & Pests** - Identify and treat problems\n📅 **Planting Schedules** - Know when to plant for best yields\n💰 **Market Prices** - Get current prices and selling tips\n🌾 **Best Practices** - Learn modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats management\n☀️ **Weather Advice** - Climate-smart farming tips\n\n**You can ask in English or Lusoga!**\nWhat would you like to know? 🚜', NULL, 'en', 'rule_based', '2026-02-05 11:38:46'),
(39, 3, 'ai_session_698481468883a5.38727573', 'tomato growing', 'I\'m here to help with agricultural questions! 😊\n\nI can assist you with:\n- **Crop Diseases & Pests** (identification and treatment)\n- **Planting Schedules** (best times and methods)\n- **Market Prices** (current rates and trends)\n- **Soil Management** (fertilizers and improvement)\n- **Weather & Climate** (farming advice)\n- **Livestock Care** (poultry, cattle, goats)\n\nPlease ask a specific question about farming, and I\'ll be happy to help! 🌾', NULL, 'en', 'rule_based', '2026-02-05 11:39:16'),
(40, 3, 'session_3_1770291638_e582fa7f44e3b36f', 'Tomato growing', '**Tomato Farming for Profit**\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 11:40:38'),
(41, 3, 'session_3_1770294896_abd65e3f29fe948f', 'hello', 'Good afternoon! 👋\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. Great to connect with you!\n\n**I can help you with:**\n🌱 **Crop Diseases** - Identify and treat problems\n📅 **Planting Schedules** - Best times to plant\n💰 **Market Prices** - Current prices and trends\n🌾 **Best Practices** - Modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats\n\nWhat would you like to know today? 😊', NULL, 'en', '', '2026-02-05 12:34:56'),
(42, 3, 'session_3_1770294922_d083bf128e70a00f', 'tomato', '**🦠 Crop Diseases & Pests**\n\n### Tomato Late Blight\n*Phytophthora infestans*\n\n**Crop:** Vegetables\n**Type:** Fungal\n**Severity:** Critical\n\n**Symptoms:**\nDark brown to black water-soaked lesions on leaves. White fuzzy fungal growth on underside of leaves (distinctive sign). Brown streaks on stems. Brown firm rot on green and ripe fruits. Entire plant can die within days. Very destructive and fast-spreading.\n\n**Treatment:**\nAGGRESSIVE treatment needed - this is emergency!\r\n1. Ridomil Gold MZ: 50g per 20L water every 7 days\r\n2. Dithane M45 (Mancozeb): 40g per 20L every 5-7 days\r\n3. Acrobat MZ: 40g per 20L water\r\n4. Copper-based fungicides as backup\r\nStart treatment at first sign. Spray entire plant thoroughly.\r\nRemove and burn infected plants. Do NOT compost.\r\nMay need to abandon severely infected fields\n\n**Prevention:**\n1. Plant resistant varieties if available\r\n2. Avoid planting near potatoes (shares same disease)\r\n3. Ensure excellent air circulation and drainage\r\n4. Avoid overhead irrigation completely\r\n5. Remove and destroy infected plants immediately\r\n6. Preventive fungicide sprays before symptoms appear\r\n7. Monitor weather - spray before rainy periods\n\n---\n\n### Tomato Late Blight\n*Phytophthora infestans*\n\n**Crop:** Vegetables\n**Type:** Fungal\n**Severity:** Critical\n\n**Symptoms:**\nDark brown to black water-soaked lesions on leaves. White fuzzy fungal growth on underside of leaves (distinctive sign). Brown streaks on stems. Brown firm rot on green and ripe fruits. Entire plant can die within days. Very destructive and fast-spreading.\n\n**Treatment:**\nAGGRESSIVE treatment needed - this is emergency!\r\n1. Ridomil Gold MZ: 50g per 20L water every 7 days\r\n2. Dithane M45 (Mancozeb): 40g per 20L every 5-7 days\r\n3. Acrobat MZ: 40g per 20L water\r\n4. Copper-based fungicides as backup\r\nStart treatment at first sign. Spray entire plant thoroughly.\r\nRemove and burn infected plants. Do NOT compost.\r\nMay need to abandon severely infected fields\n\n**Prevention:**\n1. Plant resistant varieties if available\r\n2. Avoid planting near potatoes (shares same disease)\r\n3. Ensure excellent air circulation and drainage\r\n4. Avoid overhead irrigation completely\r\n5. Remove and destroy infected plants immediately\r\n6. Preventive fungicide sprays before symptoms appear\r\n7. Monitor weather - spray before rainy periods\n\n---\n\n### Tomato Late Blight\n*Phytophthora infestans*\n\n**Crop:** Vegetables\n**Type:** Fungal\n**Severity:** High\n\n**Symptoms:**\nDark brown to black lesions on leaves and stems. White fuzzy growth on underside of leaves. Brown rot on fruits. Rapid plant death possible.\n\n**Treatment:**\nSpray with copper-based fungicides (e.g., Dithane M45, Ridomil) at first sign of disease. Repeat every 7-10 days in wet weather. Remove and destroy severely infected plants.\n\n**Prevention:**\n1. Plant resistant varieties\n2. Ensure good spacing for air circulation\n3. Avoid overhead irrigation\n4. Remove infected plants immediately\n5. Use certified disease-free seeds\n6. Practice crop rotation\n\n---\n\n⚠️ *Always consult with an agricultural extension officer for proper diagnosis*', NULL, 'en', '', '2026-02-05 12:35:22'),
(43, 3, 'session_3_1770295427_074073de225da08b', 'hello', 'Good afternoon! 👋\n\nI\'m **AIM AI**, your intelligent agricultural assistant for Uganda. Great to connect with you!\n\n**I can help you with:**\n🌱 **Crop Diseases** - Identify and treat problems\n📅 **Planting Schedules** - Best times to plant\n💰 **Market Prices** - Current prices and trends\n🌾 **Best Practices** - Modern farming techniques\n🐔 **Livestock Care** - Poultry, cattle, goats\n\nWhat would you like to know today? 😊', NULL, 'en', '', '2026-02-05 12:43:47'),
(44, 3, 'session_3_1770297602_bb3b66a4353ded7a', 'Tomato growing', '## Tomato Growing Information\n\n**🌱 Agricultural Tips**\n\n### Tomato Farming for Profit\n*Crop: Vegetables*\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n---\n\n### Hot Pepper &amp; Sweet Pepper Farming\n*Crop: Vegetables*\n\n**Growing Peppers for Profit:**\n\r\n**Types & Varieties:**\n\r\n**Hot Peppers:**\n\n\r\n\n\r\n- Bird\'s Eye (Pili Pili): Very hot, high demand\n\r\n- Cayenne: Medium hot\n\r\n- Habanero: Extremely hot, premium price\n\r\n\n\r\n**Sweet Peppers (Bell Peppers):**\n\n\r\n\n\r\n- California Wonder: Large fruits\n\r\n- Yolo Wonder: Disease resistant\n\r\n- Green/Red/Yellow varieties\n\r\n\n\r\n**Production Requirements:**\n\r\n\n\r\n- **Spacing:** 60cm x 45cm\n\r\n- **Fertilizer:** Heavy feeder like tomatoes\n\r\n- **Staking:** Recommended for heavy fruiting\n\r\n- **Irrigation:** Regular moisture needed\n\r\n- **Maturity:** 90-120 days\n\r\n\n\r\n**Pest & Disease:**\n\r\n\n\r\n- Aphids, Whiteflies: Use neem or chemical\n\r\n- Bacterial Wilt: Crop rotation essential\n\r\n- Anthracnose: Copper fungicides\n\r\n\n\r\n**Marketing:**\n\r\n\n\r\n- Hot peppers: UGX 3,000-8,000 per kg\n\r\n- Sweet peppers: UGX 2,000-5,000 per kg\n\r\n- Can be dried for longer storage\n\r\n- Export potential for quality produce\n\n---\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 13:20:02'),
(45, 3, 'session_3_1770297602_bb3b66a4353ded7a', 'tomato diseases', '## Tomato Diseases Information\n\n**🌱 Agricultural Tips**\n\n### Tomato Farming for Profit\n*Crop: Vegetables*\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n---\n\n### Hot Pepper &amp; Sweet Pepper Farming\n*Crop: Vegetables*\n\n**Growing Peppers for Profit:**\n\r\n**Types & Varieties:**\n\r\n**Hot Peppers:**\n\n\r\n\n\r\n- Bird\'s Eye (Pili Pili): Very hot, high demand\n\r\n- Cayenne: Medium hot\n\r\n- Habanero: Extremely hot, premium price\n\r\n\n\r\n**Sweet Peppers (Bell Peppers):**\n\n\r\n\n\r\n- California Wonder: Large fruits\n\r\n- Yolo Wonder: Disease resistant\n\r\n- Green/Red/Yellow varieties\n\r\n\n\r\n**Production Requirements:**\n\r\n\n\r\n- **Spacing:** 60cm x 45cm\n\r\n- **Fertilizer:** Heavy feeder like tomatoes\n\r\n- **Staking:** Recommended for heavy fruiting\n\r\n- **Irrigation:** Regular moisture needed\n\r\n- **Maturity:** 90-120 days\n\r\n\n\r\n**Pest & Disease:**\n\r\n\n\r\n- Aphids, Whiteflies: Use neem or chemical\n\r\n- Bacterial Wilt: Crop rotation essential\n\r\n- Anthracnose: Copper fungicides\n\r\n\n\r\n**Marketing:**\n\r\n\n\r\n- Hot peppers: UGX 3,000-8,000 per kg\n\r\n- Sweet peppers: UGX 2,000-5,000 per kg\n\r\n- Can be dried for longer storage\n\r\n- Export potential for quality produce\n\n---\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-05 13:21:05'),
(46, 4, 'session_4_1770446206_1512621ba306a2e5', 'price for beans', '## Beans Market Prices Information\n\n**🦠 Crop Diseases & Pests**\n\n### Bean Anthracnose\n\n**Crop:** Beans\n**Severity:** Medium\n\n**Symptoms:**\nDark brown sunken lesions on pods. Black lesions on leaves and stems. Seeds may have brown spots. Reduced pod quality.\n\n**Treatment:**\nApply fungicides like Benomyl or Mancozeb at flowering and repeat every 10-14 days. Remove severely infected plants. Harvest in dry weather.\n\n**Prevention:**\n1. Use certified disease-free seeds\n2. Practice 2-year crop rotation\n3. Destroy crop residues\n4. Plant in well-drained areas\n5. Avoid working in wet fields\n\n---\n\n### Bean Rust\n\n**Crop:** Beans\n**Severity:** Medium\n\n**Symptoms:**\nSmall reddish-brown pustules on leaves, yellowing and premature leaf drop\n\n**Treatment:**\nApply fungicides (Mancozeb or copper-based), remove infected leaves\n\n**Prevention:**\nPlant resistant varieties, ensure good air circulation, avoid overhead irrigation\n\n---\n\n⚠️ *Always consult with an agricultural extension officer for proper diagnosis*', NULL, 'en', '', '2026-02-07 06:36:46');
INSERT INTO `ai_conversations` (`id`, `user_id`, `session_id`, `message`, `response`, `context_data`, `language`, `source`, `created_at`) VALUES
(47, 4, 'session_4_1770446206_1512621ba306a2e5', 'how to grow tomatoes', '## Tomato Growing Information\n\n**🌱 Agricultural Tips**\n\n### Tomato Farming for Profit\n*Crop: Vegetables*\n\n**High-Yield Tomato Production:**\n\r\n**Variety Selection:**\n\r\n\n\r\n- **Hybrids:** Anna F1, Kilele F1, Eden F1 (30-50 tons/acre)\n\r\n- **Open Pollinated:** Money Maker, Roma VF (15-25 tons/acre)\n\r\n\n\r\n**Critical Success Factors:**\n\r\n\n\r\n- **Staking:** Install within 1 week of transplanting\n\r\n- **Pruning:** Remove suckers weekly, train to 1-2 stems\n\r\n- **Spraying:** Weekly fungicide/insecticide rotation\n\r\n- **Fertilization:** Base: 200kg NPK, Top: 200kg CAN in splits\n\r\n- **Irrigation:** Drip system ideal, 2-3 times per week\n\r\n\n\r\n**Economic Returns (1 acre):**\n\r\n\n\r\n- Investment: UGX 3.3 million\n\r\n- Yield: 35 tons (hybrid)\n\r\n- Revenue: UGX 52-122 million\n\r\n- Net profit: UGX 50-120 million!\n\r\n\n\r\n**Harvest period:** 10-16 weeks after transplanting, pick every 2-3 days\n\n---\n\n### Hot Pepper &amp; Sweet Pepper Farming\n*Crop: Vegetables*\n\n**Growing Peppers for Profit:**\n\r\n**Types & Varieties:**\n\r\n**Hot Peppers:**\n\n\r\n\n\r\n- Bird\'s Eye (Pili Pili): Very hot, high demand\n\r\n- Cayenne: Medium hot\n\r\n- Habanero: Extremely hot, premium price\n\r\n\n\r\n**Sweet Peppers (Bell Peppers):**\n\n\r\n\n\r\n- California Wonder: Large fruits\n\r\n- Yolo Wonder: Disease resistant\n\r\n- Green/Red/Yellow varieties\n\r\n\n\r\n**Production Requirements:**\n\r\n\n\r\n- **Spacing:** 60cm x 45cm\n\r\n- **Fertilizer:** Heavy feeder like tomatoes\n\r\n- **Staking:** Recommended for heavy fruiting\n\r\n- **Irrigation:** Regular moisture needed\n\r\n- **Maturity:** 90-120 days\n\r\n\n\r\n**Pest & Disease:**\n\r\n\n\r\n- Aphids, Whiteflies: Use neem or chemical\n\r\n- Bacterial Wilt: Crop rotation essential\n\r\n- Anthracnose: Copper fungicides\n\r\n\n\r\n**Marketing:**\n\r\n\n\r\n- Hot peppers: UGX 3,000-8,000 per kg\n\r\n- Sweet peppers: UGX 2,000-5,000 per kg\n\r\n- Can be dried for longer storage\n\r\n- Export potential for quality produce\n\n---\n\n💡 *Source: AIMS Agricultural Knowledge Base*', NULL, 'en', '', '2026-02-07 06:37:55');

--
-- Triggers `ai_conversations`
--
DELIMITER $$
CREATE TRIGGER `update_session_context_after_conversation` AFTER INSERT ON `ai_conversations` FOR EACH ROW BEGIN
    -- Only process if session_id is not null
    IF NEW.session_id IS NOT NULL THEN
        INSERT INTO ai_session_context 
          (session_id, user_id, topics_discussed, last_topic, updated_at)
        VALUES (
            NEW.session_id, 
            NEW.user_id, 
            JSON_ARRAY(LEFT(NEW.message, 100)),
            LEFT(NEW.message, 100),
            NOW()
        )
        ON DUPLICATE KEY UPDATE
            topics_discussed = JSON_ARRAY_APPEND(
                topics_discussed, 
                '$', 
                LEFT(VALUES(last_topic), 100)
            ),
            last_topic = VALUES(last_topic),
            updated_at = NOW();
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `ai_conversation_feedback`
--

CREATE TABLE `ai_conversation_feedback` (
  `id` int(11) NOT NULL,
  `conversation_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `rating` enum('helpful','not_helpful','incorrect') NOT NULL,
  `feedback_text` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `ai_knowledge_sources`
--

CREATE TABLE `ai_knowledge_sources` (
  `id` int(11) NOT NULL,
  `source_type` enum('database','api','manual','learned') NOT NULL,
  `source_name` varchar(100) NOT NULL,
  `query_pattern` text DEFAULT NULL,
  `response_template` text DEFAULT NULL,
  `priority` int(11) DEFAULT 5,
  `is_active` tinyint(1) DEFAULT 1,
  `success_count` int(11) DEFAULT 0,
  `failure_count` int(11) DEFAULT 0,
  `avg_response_time` decimal(10,2) DEFAULT 0.00,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `ai_knowledge_sources`
--

INSERT INTO `ai_knowledge_sources` (`id`, `source_type`, `source_name`, `query_pattern`, `response_template`, `priority`, `is_active`, `success_count`, `failure_count`, `avg_response_time`, `created_at`, `updated_at`) VALUES
(1, 'database', 'agricultural_tips', NULL, NULL, 10, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(2, 'database', 'crop_diseases', NULL, NULL, 9, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(3, 'database', 'farming_schedules', NULL, NULL, 8, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(4, 'database', 'market_prices', NULL, NULL, 7, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(5, 'database', 'crop_varieties', NULL, NULL, 6, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(6, 'manual', 'knowledge_base_english', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(7, 'manual', 'knowledge_base_lusoga', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(8, 'api', 'openai', NULL, NULL, 3, 1, 0, 0, 0.00, '2026-02-03 08:00:48', '2026-02-03 08:00:48'),
(9, 'database', 'agricultural_tips', NULL, NULL, 10, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(10, 'database', 'crop_diseases', NULL, NULL, 9, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(11, 'database', 'farming_schedules', NULL, NULL, 8, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(12, 'database', 'market_prices', NULL, NULL, 7, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(13, 'database', 'crop_varieties', NULL, NULL, 6, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(14, 'manual', 'knowledge_base_english', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(15, 'manual', 'knowledge_base_lusoga', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(16, 'api', 'openai', NULL, NULL, 3, 1, 0, 0, 0.00, '2026-02-03 09:00:04', '2026-02-03 09:00:04'),
(17, 'database', 'agricultural_tips', NULL, NULL, 10, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(18, 'database', 'crop_diseases', NULL, NULL, 9, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(19, 'database', 'farming_schedules', NULL, NULL, 8, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(20, 'database', 'market_prices', NULL, NULL, 7, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(21, 'database', 'crop_varieties', NULL, NULL, 6, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(22, 'manual', 'knowledge_base_english', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(23, 'manual', 'knowledge_base_lusoga', NULL, NULL, 5, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18'),
(24, 'api', 'openai', NULL, NULL, 3, 1, 0, 0, 0.00, '2026-02-03 09:04:18', '2026-02-03 09:04:18');

-- --------------------------------------------------------

--
-- Table structure for table `ai_learned_patterns`
--

CREATE TABLE `ai_learned_patterns` (
  `id` int(11) NOT NULL,
  `question_pattern` text NOT NULL,
  `response_template` text NOT NULL,
  `language` enum('en','lusoga') NOT NULL DEFAULT 'en',
  `source` enum('openai','user_feedback','admin','system') NOT NULL DEFAULT 'system',
  `usage_count` int(11) DEFAULT 0,
  `success_rate` decimal(3,2) DEFAULT 1.00,
  `last_used` timestamp NULL DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `ai_session_context`
--

CREATE TABLE `ai_session_context` (
  `id` int(11) NOT NULL,
  `session_id` varchar(100) NOT NULL,
  `user_id` int(11) NOT NULL,
  `context_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`context_data`)),
  `topics_discussed` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`topics_discussed`)),
  `last_topic` varchar(100) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `ai_session_context`
--

INSERT INTO `ai_session_context` (`id`, `session_id`, `user_id`, `context_data`, `topics_discussed`, `last_topic`, `created_at`, `updated_at`) VALUES
(1, 'session_3_1770112685_fe7c612730000e52', 3, NULL, '[\"tomato diseases\", \"poultry diseases\", \"poultry diseases\"]', 'poultry diseases', '2026-02-03 09:58:07', '2026-02-03 11:01:17'),
(4, 'session_3_1770129862_bbe17faa921e5c85', 3, NULL, '[\"Tomato growing\", \"poultry keeping\", \"cassava diseases\"]', 'cassava diseases', '2026-02-03 14:44:22', '2026-02-03 14:45:41'),
(7, 'session_3_1770129986_18eb88d8acaa1008', 3, NULL, '[\"cassava growing\"]', 'cassava growing', '2026-02-03 14:46:27', '2026-02-03 14:46:27'),
(8, 'session_3_1770130170_b7f72fe9ee72611e', 3, NULL, '[\"what are the tomato diseases\"]', 'what are the tomato diseases', '2026-02-03 14:49:30', '2026-02-03 14:49:30'),
(9, 'session_3_1770266734_b7d55e199ae706b5', 3, NULL, '[\"what are the tomato diseases\", \"diseases affecting tomatoes\"]', 'diseases affecting tomatoes', '2026-02-05 04:45:34', '2026-02-05 04:46:28'),
(11, 'session_3_1770272999_af2a7dc8bcff46fd', 3, NULL, '[\"Best time to plant maize\", \"maize diseases\"]', 'maize diseases', '2026-02-05 06:29:59', '2026-02-05 06:30:27'),
(13, 'session_3_1770291314_f73fd51f347d8a9d', 3, NULL, '[\"hello\", \"tomato diseases\"]', 'tomato diseases', '2026-02-05 11:35:14', '2026-02-05 11:35:40'),
(15, 'session_3_1770291398_5665901072123512', 3, NULL, '[\"hi\", \"tomoto diseases\", \"tomato growing\"]', 'tomato growing', '2026-02-05 11:36:42', '2026-02-05 11:37:46'),
(18, 'ai_session_698481468883a5.38727573', 3, NULL, '[\"hello\", \"tomato growing\"]', 'tomato growing', '2026-02-05 11:38:46', '2026-02-05 11:39:16'),
(20, 'session_3_1770291638_e582fa7f44e3b36f', 3, NULL, '[\"Tomato growing\"]', 'Tomato growing', '2026-02-05 11:40:38', '2026-02-05 11:40:38'),
(21, 'session_3_1770294896_abd65e3f29fe948f', 3, NULL, '[\"hello\"]', 'hello', '2026-02-05 12:34:56', '2026-02-05 12:34:56'),
(22, 'session_3_1770294922_d083bf128e70a00f', 3, NULL, '[\"tomato\"]', 'tomato', '2026-02-05 12:35:22', '2026-02-05 12:35:22'),
(23, 'session_3_1770295427_074073de225da08b', 3, NULL, '[\"hello\"]', 'hello', '2026-02-05 12:43:47', '2026-02-05 12:43:47'),
(24, 'session_3_1770297602_bb3b66a4353ded7a', 3, NULL, '[\"Tomato growing\", \"tomato diseases\"]', 'tomato diseases', '2026-02-05 13:20:02', '2026-02-05 13:21:05'),
(26, 'session_4_1770446206_1512621ba306a2e5', 4, NULL, '[\"price for beans\", \"how to grow tomatoes\"]', 'how to grow tomatoes', '2026-02-07 06:36:46', '2026-02-07 06:37:55');

-- --------------------------------------------------------

--
-- Table structure for table `api_rate_limits`
--

CREATE TABLE `api_rate_limits` (
  `id` int(11) NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `ip_address` varchar(45) NOT NULL,
  `endpoint` varchar(255) NOT NULL,
  `request_count` int(11) DEFAULT 1,
  `window_start` timestamp NULL DEFAULT current_timestamp(),
  `is_blocked` tinyint(1) DEFAULT 0,
  `block_expires_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `backup_restorations`
--

CREATE TABLE `backup_restorations` (
  `id` int(11) NOT NULL,
  `backup_id` int(11) NOT NULL,
  `restored_by` int(11) NOT NULL,
  `restoration_type` enum('full','partial','test') DEFAULT 'full',
  `tables_restored` text DEFAULT NULL,
  `status` enum('in_progress','completed','failed','rolled_back') DEFAULT 'in_progress',
  `records_restored` int(11) DEFAULT 0,
  `error_message` text DEFAULT NULL,
  `started_at` timestamp NULL DEFAULT current_timestamp(),
  `completed_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `bulk_orders`
--

CREATE TABLE `bulk_orders` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `order_title` varchar(200) NOT NULL,
  `product_type` varchar(100) NOT NULL,
  `total_quantity` decimal(12,2) NOT NULL,
  `unit` varchar(20) DEFAULT 'kg',
  `budget_per_unit` decimal(10,2) DEFAULT NULL,
  `delivery_deadline` date DEFAULT NULL,
  `delivery_location` varchar(200) DEFAULT NULL,
  `special_requirements` text DEFAULT NULL,
  `status` enum('open','in_progress','completed','cancelled') DEFAULT 'open',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `bulk_order_bids`
--

CREATE TABLE `bulk_order_bids` (
  `id` int(11) NOT NULL,
  `bulk_order_id` int(11) NOT NULL,
  `farmer_id` int(11) NOT NULL,
  `quantity_offered` decimal(10,2) NOT NULL,
  `price_per_unit` decimal(10,2) NOT NULL,
  `delivery_date` date DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `status` enum('pending','accepted','rejected') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `buyer_payment_methods`
--

CREATE TABLE `buyer_payment_methods` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `payment_type` enum('mobile_money','bank_transfer','cash','credit') DEFAULT 'mobile_money',
  `account_name` varchar(200) DEFAULT NULL,
  `account_number` varchar(100) DEFAULT NULL,
  `bank_name` varchar(100) DEFAULT NULL,
  `mobile_network` varchar(50) DEFAULT NULL,
  `is_default` tinyint(1) DEFAULT 0,
  `is_verified` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `buyer_preferences`
--

CREATE TABLE `buyer_preferences` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `preferred_product_categories` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`preferred_product_categories`)),
  `preferred_regions` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`preferred_regions`)),
  `minimum_quality_grade` varchar(10) DEFAULT 'B',
  `auto_reject_below_rating` decimal(2,1) DEFAULT 3.0,
  `email_notifications` tinyint(1) DEFAULT 1,
  `sms_notifications` tinyint(1) DEFAULT 1,
  `price_alert_notifications` tinyint(1) DEFAULT 1,
  `new_supplier_alerts` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `buyer_profiles`
--

CREATE TABLE `buyer_profiles` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `buyer_type` enum('individual','retailer','wholesaler','processor','exporter') NOT NULL,
  `business_name` varchar(200) DEFAULT NULL,
  `business_registration` varchar(100) DEFAULT NULL,
  `business_description` text DEFAULT NULL,
  `tax_id` varchar(50) DEFAULT NULL,
  `business_address` text DEFAULT NULL,
  `business_phone` varchar(15) DEFAULT NULL,
  `business_email` varchar(100) DEFAULT NULL,
  `business_website` varchar(255) DEFAULT NULL,
  `preferred_products` text DEFAULT NULL COMMENT 'JSON array of product categories',
  `categories_of_interest` text DEFAULT NULL COMMENT 'JSON array of product categories',
  `business_district` int(11) DEFAULT NULL,
  `buying_capacity` varchar(50) DEFAULT NULL COMMENT 'Small, Medium, Large',
  `preferred_payment_method` text DEFAULT NULL COMMENT 'JSON array of payment methods',
  `delivery_preference` enum('pickup','delivery','flexible') DEFAULT 'pickup',
  `license_documents` text DEFAULT NULL COMMENT 'JSON array of license URLs',
  `is_verified` tinyint(1) DEFAULT 0,
  `is_profile_complete` tinyint(1) DEFAULT 0,
  `verification_date` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `buyer_profiles`
--

INSERT INTO `buyer_profiles` (`id`, `user_id`, `buyer_type`, `business_name`, `business_registration`, `business_description`, `tax_id`, `business_address`, `business_phone`, `business_email`, `business_website`, `preferred_products`, `categories_of_interest`, `business_district`, `buying_capacity`, `preferred_payment_method`, `delivery_preference`, `license_documents`, `is_verified`, `is_profile_complete`, `verification_date`, `created_at`, `updated_at`) VALUES
(1, 4, 'wholesaler', 'MJ Agro Processors LTD', 'B14202613', 'All Cereals like Maize,Rice,Beans', '1420261235', 'Located in Kiyunga Town Luuka District', '+256758697337', 'mjagroprocessors@gmail.com', NULL, NULL, '[\"Grains & Cereals\"]', 1, 'large', 'cash', 'flexible', NULL, 0, 1, NULL, '2026-02-05 05:30:58', '2026-02-05 05:30:58');

-- --------------------------------------------------------

--
-- Table structure for table `buyer_watchlist`
--

CREATE TABLE `buyer_watchlist` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `product_type` varchar(100) NOT NULL,
  `target_price` decimal(10,2) DEFAULT NULL,
  `alert_when` enum('below','above') DEFAULT 'below',
  `preferred_suppliers` text DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `last_notification` date DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `chats`
--

CREATE TABLE `chats` (
  `id` int(11) NOT NULL,
  `chat_type` enum('group','one_to_one') NOT NULL,
  `chat_name` varchar(100) DEFAULT NULL,
  `chat_avatar` varchar(255) DEFAULT NULL,
  `created_by` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `chats`
--

INSERT INTO `chats` (`id`, `chat_type`, `chat_name`, `chat_avatar`, `created_by`, `created_at`, `updated_at`) VALUES
(1, 'one_to_one', NULL, NULL, 9, '2026-02-05 20:54:05', '2026-02-07 06:25:03');

-- --------------------------------------------------------

--
-- Table structure for table `chat_encryption_keys`
--

CREATE TABLE `chat_encryption_keys` (
  `id` int(11) NOT NULL,
  `chat_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `encrypted_key` text NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `chat_members`
--

CREATE TABLE `chat_members` (
  `id` int(11) NOT NULL,
  `chat_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `role` enum('admin','member') DEFAULT 'member',
  `joined_at` timestamp NULL DEFAULT current_timestamp(),
  `last_read_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `chat_members`
--

INSERT INTO `chat_members` (`id`, `chat_id`, `user_id`, `role`, `joined_at`, `last_read_at`) VALUES
(1, 1, 3, 'admin', '2026-01-31 08:40:34', '2026-02-07 06:25:28'),
(2, 1, 9, 'member', '2026-02-05 20:54:05', '2026-02-07 06:27:59');

--
-- Triggers `chat_members`
--
DELIMITER $$
CREATE TRIGGER `audit_chat_member_add` AFTER INSERT ON `chat_members` FOR EACH ROW BEGIN
    INSERT INTO chat_member_audit (chat_id, user_id, action, added_by)
    VALUES (NEW.chat_id, NEW.user_id, 'added', @current_user_id);
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `audit_chat_member_remove` AFTER DELETE ON `chat_members` FOR EACH ROW BEGIN
    INSERT INTO chat_member_audit (chat_id, user_id, action, added_by)
    VALUES (OLD.chat_id, OLD.user_id, 'removed', @current_user_id);
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `validate_one_on_one_members` BEFORE INSERT ON `chat_members` FOR EACH ROW BEGIN
    DECLARE chat_type_val VARCHAR(20);
    DECLARE member_count INT;
    
    -- Get chat type
    SELECT chat_type INTO chat_type_val 
    FROM chats 
    WHERE id = NEW.chat_id;
    
    -- For one-to-one chats, ensure max 2 members
    IF chat_type_val = 'one_to_one' THEN
        SELECT COUNT(*) INTO member_count
        FROM chat_members
        WHERE chat_id = NEW.chat_id;
        
        IF member_count >= 2 THEN
            SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'One-to-one chat can only have 2 members';
        END IF;
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `chat_member_audit`
--

CREATE TABLE `chat_member_audit` (
  `id` int(11) NOT NULL,
  `chat_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `action` enum('added','removed') NOT NULL,
  `added_by` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `comment_likes`
--

CREATE TABLE `comment_likes` (
  `id` int(11) NOT NULL,
  `comment_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `comment_likes`
--
DELIMITER $$
CREATE TRIGGER `decrease_comment_likes_count` AFTER DELETE ON `comment_likes` FOR EACH ROW BEGIN
    UPDATE post_comments SET likes_count = likes_count - 1 WHERE id = OLD.comment_id;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_comment_likes_count` AFTER INSERT ON `comment_likes` FOR EACH ROW BEGIN
    UPDATE post_comments SET likes_count = likes_count + 1 WHERE id = NEW.comment_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `contract_deliveries`
--

CREATE TABLE `contract_deliveries` (
  `id` int(11) NOT NULL,
  `contract_id` int(11) NOT NULL,
  `delivery_number` varchar(50) NOT NULL,
  `quantity_delivered` decimal(10,2) NOT NULL,
  `delivery_date` date NOT NULL,
  `quality_grade` enum('A','B','C','rejected') DEFAULT 'A',
  `quality_notes` text DEFAULT NULL,
  `inspection_report` varchar(255) DEFAULT NULL,
  `amount_paid` decimal(10,2) DEFAULT 0.00,
  `payment_date` date DEFAULT NULL,
  `status` enum('pending','accepted','rejected') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `crop_diseases`
--

CREATE TABLE `crop_diseases` (
  `id` int(11) NOT NULL,
  `disease_name` varchar(200) NOT NULL,
  `scientific_name` varchar(200) DEFAULT NULL,
  `crop_type` varchar(50) NOT NULL,
  `category` enum('fungal','bacterial','viral','pest','nutritional') NOT NULL,
  `symptoms` text NOT NULL,
  `causes` text NOT NULL,
  `prevention` text NOT NULL,
  `treatment` text NOT NULL,
  `severity_level` enum('low','medium','high','critical') DEFAULT 'medium',
  `affected_parts` varchar(255) DEFAULT NULL COMMENT 'leaves, stems, roots, etc.',
  `spread_method` text DEFAULT NULL,
  `optimal_conditions` text DEFAULT NULL COMMENT 'Conditions favorable for disease',
  `images` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`images`)),
  `language` enum('en','lusoga') DEFAULT 'en',
  `created_by` int(11) DEFAULT NULL,
  `is_published` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `crop_diseases`
--

INSERT INTO `crop_diseases` (`id`, `disease_name`, `scientific_name`, `crop_type`, `category`, `symptoms`, `causes`, `prevention`, `treatment`, `severity_level`, `affected_parts`, `spread_method`, `optimal_conditions`, `images`, `language`, `created_by`, `is_published`, `created_at`, `updated_at`) VALUES
(1, 'Maize Streak Virus', 'Maize streak virus (MSV)', 'maize', 'viral', 'Yellow streaks along leaf veins, stunted growth, reduced yield', 'Transmitted by leafhoppers (Cicadulina species)', 'Plant resistant varieties, control leafhopper population, remove infected plants early', 'No cure available - focus on prevention, remove infected plants', 'high', 'leaves', 'Transmitted by leafhopper insects', NULL, NULL, 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(2, 'Cassava Mosaic Disease', 'Cassava mosaic virus (CMV)', 'cassava', 'viral', 'Yellow mottling on leaves, leaf distortion, stunted growth', 'Spread by whiteflies and infected cuttings', 'Use disease-free planting material, control whitefly population, plant resistant varieties', 'Remove and destroy infected plants, use clean planting material', 'critical', 'leaves', 'Whitefly transmission and infected planting material', NULL, NULL, 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(3, 'Bean Rust', 'Uromyces appendiculatus', 'beans', 'fungal', 'Small reddish-brown pustules on leaves, yellowing and premature leaf drop', 'Fungal pathogen favored by warm, humid conditions', 'Plant resistant varieties, ensure good air circulation, avoid overhead irrigation', 'Apply fungicides (Mancozeb or copper-based), remove infected leaves', 'medium', 'leaves, pods', 'Wind-borne spores, water splash', NULL, NULL, 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(4, 'Banana Bacterial Wilt', 'Xanthomonas campestris', 'bananas', 'bacterial', 'Yellowing of leaves, wilting, fruit rot, bacterial ooze', 'Bacterial infection through wounds, contaminated tools', 'Use clean tools, remove male buds early, destroy infected plants', 'No cure - remove and bury infected plants deep, quarantine area', 'critical', 'entire plant', 'Contaminated tools, insects, infected planting material', NULL, NULL, 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(5, 'Tomato Late Blight', 'Phytophthora infestans', 'vegetables', 'fungal', 'Dark brown to black lesions on leaves and stems. White fuzzy growth on underside of leaves. Brown rot on fruits. Rapid plant death possible.', 'Fungal infection favored by cool, wet weather. Spreads rapidly in humid conditions with temperatures 10-25°C.', '1. Plant resistant varieties\n2. Ensure good spacing for air circulation\n3. Avoid overhead irrigation\n4. Remove infected plants immediately\n5. Use certified disease-free seeds\n6. Practice crop rotation', 'Spray with copper-based fungicides (e.g., Dithane M45, Ridomil) at first sign of disease. Repeat every 7-10 days in wet weather. Remove and destroy severely infected plants.', 'high', 'leaves, stems, fruits', 'Wind-borne spores, water splash, infected plant material', 'Cool temperatures (10-25°C), high humidity (>90%), prolonged leaf wetness', NULL, 'en', NULL, 1, '2026-02-02 19:32:43', '2026-02-02 19:32:43'),
(6, 'Coffee Wilt Disease', 'Fusarium xylarioides', 'coffee', 'fungal', 'Wilting of leaves starting from branch tips. Green leaves fall off. Brown streaks in wood when cut. Eventual tree death.', 'Soil-borne fungus that blocks water transport in plants. Spreads through infected tools, soil, and planting material.', '1. Use resistant varieties\n2. Remove and burn infected trees\n3. Sanitize pruning tools between plants\n4. Practice good field sanitation\n5. Avoid injuring roots during weeding', 'No cure available. Remove and burn infected trees immediately. Treat surrounding soil with fungicide. Do not replant coffee in same spot for 2-3 years.', 'critical', 'entire plant, vascular system', 'Contaminated tools, infected soil, diseased planting material', 'Stressed plants, wounded roots, poor drainage', NULL, 'en', NULL, 1, '2026-02-02 19:32:43', '2026-02-02 19:32:43'),
(7, 'Bean Anthracnose', 'Colletotrichum lindemuthianum', 'beans', 'fungal', 'Dark brown sunken lesions on pods. Black lesions on leaves and stems. Seeds may have brown spots. Reduced pod quality.', 'Fungal disease spread by contaminated seeds and splash water. Favored by warm humid conditions.', '1. Use certified disease-free seeds\n2. Practice 2-year crop rotation\n3. Destroy crop residues\n4. Plant in well-drained areas\n5. Avoid working in wet fields', 'Apply fungicides like Benomyl or Mancozeb at flowering and repeat every 10-14 days. Remove severely infected plants. Harvest in dry weather.', 'medium', 'pods, leaves, stems, seeds', 'Contaminated seeds, water splash, wind', 'Warm humid weather (20-27°C), frequent rain, dense plant canopy', NULL, 'en', NULL, 1, '2026-02-02 19:32:43', '2026-02-02 19:32:43'),
(8, 'Cassava Brown Streak Disease (CBSD)', 'Cassava brown streak virus', 'cassava', 'viral', 'Yellow/brown streaks on stems. Irregular chlorotic blotches on leaves. Brown corky rot in roots making them unmarketable.', 'Viral disease spread by whiteflies. No cure exists. Severely affects root quality and yields.', '1. Use clean, disease-free planting material\n2. Control whitefly populations\n3. Remove infected plants\n4. Plant resistant varieties (NASE 19)\n5. Intercrop with non-host plants', 'No cure available. Remove and destroy infected plants immediately. Use insecticides to control whiteflies. Plant only resistant varieties.', 'critical', 'stems, leaves, storage roots', 'Whitefly transmission, infected planting material', 'Warm conditions, high whitefly populations, stressed plants', NULL, 'en', NULL, 1, '2026-02-02 19:32:43', '2026-02-02 19:32:43'),
(9, 'Maize Leaf Blight', 'Helminthosporium turcicum', 'maize', 'fungal', 'Long elliptical tan lesions on leaves with dark borders. Lesions may merge causing large dead areas. Severe cases lead to premature leaf death.', 'Fungal infection favored by moderate temperatures and high humidity. Spreads through wind and rain splash.', '1. Plant resistant hybrids\n2. Practice crop rotation\n3. Deep ploughing of crop residues\n4. Ensure proper plant spacing\n5. Apply balanced fertilizer', 'Spray with fungicides (Mancozeb, Benomyl) when first spots appear. Repeat every 10-14 days if conditions favor disease. Ensure good plant nutrition.', 'medium', 'leaves', 'Wind-borne spores, rain splash, infected crop residues', 'Temperatures 18-27°C, high humidity, overnight dew', NULL, 'en', NULL, 1, '2026-02-02 19:32:43', '2026-02-02 19:32:43'),
(10, 'Newcastle Disease', 'Avian paramyxovirus type 1', 'poultry', 'viral', 'Respiratory distress (gasping, coughing, sneezing). Greenish watery diarrhea. Twisted neck, paralysis, wing drooping. Sudden death. Drop in egg production up to 50%. Soft-shelled eggs. Mortality can reach 100% in unvaccinated flocks.', 'Highly contagious viral disease spread through respiratory secretions, feces, contaminated equipment, wild birds, and human clothing. Virus survives in environment for weeks.', '1. Strict vaccination schedule (Day 7, Day 21, then every 2-3 months)\r\n2. Strong biosecurity: footbaths, limited visitors, all-in all-out system\r\n3. Quarantine new birds for 14 days\r\n4. Clean and disinfect between batches\r\n5. Proper disposal of dead birds\r\n6. Control wild bird access', 'NO CURE - virus is fatal. Supportive care only:\r\n- Broad spectrum antibiotics (Oxytetracycline, Enrofloxacin) prevent secondary bacterial infections\r\n- Multivitamins in water to boost immunity\r\n- Electrolytes to prevent dehydration\r\n- Isolate sick birds immediately\r\n- Report outbreak to authorities', 'critical', 'respiratory system, nervous system, digestive system', 'Airborne, fecal-oral, fomites, wild birds', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(11, 'Infectious Coryza', 'Avibacterium paragallinarum', 'poultry', 'bacterial', 'Watery nasal discharge progressing to thick, foul-smelling mucus. Severe facial swelling around eyes and wattles. Conjunctivitis (red, swollen eyes). Reduced appetite and water intake. Drop in egg production (10-40%). Difficulty breathing.', 'Bacterial infection spread through direct contact with infected birds, contaminated water, equipment. Worsened by poor ventilation, overcrowding, stress, ammonia buildup, and vitamin A deficiency.', '1. Purchase birds from disease-free sources\r\n2. Maintain good ventilation without drafts\r\n3. Avoid overcrowding (proper stocking density)\r\n4. Provide adequate vitamin A in diet\r\n5. Keep litter dry to reduce ammonia\r\n6. Quarantine new birds\r\n7. Consider vaccination in endemic areas', '1. Sulfadimethoxine in drinking water (1g per liter for 3-5 days)\r\n2. Tylosin injection (10-20mg/kg body weight)\r\n3. Erythromycin in feed (200g per ton for 7-14 days)\r\n4. Oxytetracycline (500mg per liter of water)\r\nTreatment duration: Minimum 3-5 days, continue 2 days after symptoms disappear\r\nImprove ventilation and reduce stocking density', 'high', 'respiratory system, face, eyes', 'Direct contact, aerosol, contaminated water and equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(12, 'Fowl Pox', 'Avipoxvirus', 'poultry', 'viral', 'Warty, yellowish nodules on unfeathered parts: comb, wattles, around eyes, beak, legs. Scabs form and fall off after 2-3 weeks. Diphtheritic form: Yellow patches in mouth, throat causing difficulty breathing and eating. Reduced egg production. Slow growth in young birds.', 'Viral disease transmitted by mosquitoes (primary), biting flies, mites. Also spreads through skin abrasions, cannibalism, contaminated equipment. Virus can persist in scabs for months.', '1. Vaccinate all birds at 6-8 weeks of age (wing web stab method)\r\n2. Control mosquitoes: remove standing water, use mosquito nets\r\n3. Control external parasites (mites, lice)\r\n4. Prevent fighting and cannibalism\r\n5. Isolate infected birds\r\n6. Disinfect equipment between flocks', 'NO specific antiviral treatment. Supportive care:\r\n1. Remove scabs carefully, apply iodine or gentian violet\r\n2. Broad spectrum antibiotics prevent secondary bacterial infections\r\n3. Multivitamins and vitamin A supplementation\r\n4. Improve nutrition\r\n5. For diphtheritic form: glycerin or honey in throat\r\nDisease is self-limiting, lasts 2-4 weeks', 'medium', 'skin, mucous membranes, respiratory system', 'Mosquitoes, biting insects, direct contact, contaminated equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(13, 'Coccidiosis', 'Eimeria species', 'poultry', 'pest', 'Bloody or brownish diarrhea (distinctive sign). Ruffled feathers, hunched posture. Reduced feed and water intake. Pale comb and wattles. Huddling near heat source. Slow growth in chicks. Sudden death in severe cases. Dehydration.', 'Caused by Eimeria protozoan parasites that damage intestinal lining. Oocysts shed in feces contaminate litter, water, feed. Worsened by wet litter, poor sanitation, overcrowding. Young birds (2-8 weeks) most susceptible.', '1. Keep litter dry - essential for control\r\n2. Ensure good drainage and ventilation\r\n3. Use coccidiostats in starter feed\r\n4. Avoid overcrowding\r\n5. Regular cleaning of feeders and drinkers\r\n6. Build immunity through controlled exposure\r\n7. Consider vaccination (Coccivac)', 'Anticoccidial medications:\r\n1. Amprolium (Amprol): 1ml per liter of water for 5-7 days\r\n2. Sulfadimidine: 1g per liter for 5-7 days\r\n3. Toltrazuril (Baycox): 7ml per liter for 2 consecutive days\r\n4. Diclazuril\r\nAdd multivitamins (especially K for blood clotting)\r\nRemove wet litter immediately\r\nTreatment must continue full course', 'high', 'intestines', 'Fecal-oral through contaminated litter, water, feed', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(14, 'Gumboro Disease', 'Infectious bursa disease virus (IBDV)', 'poultry', 'viral', 'Sudden onset in 3-6 week old chicks. Ruffled feathers, depression. Trembling, loss of balance. Whitish watery diarrhea, vent pecking. Prostration before death. Rapid spread through flock. High mortality (30-60%). Survivors have weakened immune system.', 'Highly contagious viral disease affecting bursa of Fabricius (immune organ). Spreads through feces, contaminated equipment, feed, water, people. Virus very stable, survives months in environment. Maternal antibodies protect first 2-3 weeks.', '1. Vaccinate: Day 14 and Day 21-28 (two doses essential)\r\n2. Use intermediate or intermediate-plus vaccines\r\n3. All-in, all-out management system\r\n4. Thorough cleaning and disinfection between batches\r\n5. Use virucidal disinfectants (formaldehyde, virkon-S)\r\n6. Footbaths at farm entrance\r\n7. Control rodents and wild birds', 'NO specific cure - virus is fatal. Management:\r\n1. Broad spectrum antibiotics prevent secondary infections\r\n2. Multivitamins and vitamin K in water\r\n3. Electrolytes for dehydration\r\n4. Maintain good husbandry\r\n5. Cull severely affected birds\r\n6. Vaccinate unaffected birds if not done\r\nBirds that recover have lifelong immunosuppression', 'critical', 'bursa of Fabricius (immune organ), digestive system', 'Highly contagious through feces, contaminated fomites, feed, water', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(15, 'Tomato Early Blight', 'Alternaria solani', 'vegetables', 'fungal', 'Brown to black spots on older lower leaves with concentric rings (target-like pattern). Spots enlarge and leaves turn yellow then die. Lesions on stems near soil line. Fruit spots near stem end. Disease progresses upward if not controlled.', 'Fungal disease favored by warm (24-29°C), wet conditions. Spreads through rain splash, irrigation water, wind, contaminated tools. Overwinters in crop debris and soil. Stressed plants more susceptible.', '1. Use disease-free transplants and certified seeds\r\n2. Crop rotation (3 years minimum)\r\n3. Remove and destroy old crop debris\r\n4. Mulch to prevent soil splash\r\n5. Avoid overhead irrigation or irrigate early morning\r\n6. Ensure adequate plant spacing for air circulation\r\n7. Balanced fertilization - avoid excess nitrogen', 'Fungicide program:\r\n1. Mancozeb 80% WP: 40g per 20L water, spray every 7-10 days\r\n2. Copper oxychloride: 50g per 20L water\r\n3. Alternate fungicides to prevent resistance\r\n4. Start preventive sprays 2-3 weeks after transplanting\r\n5. Ensure good coverage, especially lower leaves\r\n6. Remove severely infected leaves\r\nCombined with good cultural practices', 'medium', 'leaves, stems, fruits', 'Water splash, wind, contaminated tools and equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(16, 'Tomato Late Blight', 'Phytophthora infestans', 'vegetables', 'fungal', 'Dark brown to black water-soaked lesions on leaves. White fuzzy fungal growth on underside of leaves (distinctive sign). Brown streaks on stems. Brown firm rot on green and ripe fruits. Entire plant can die within days. Very destructive and fast-spreading.', 'Fungal disease favored by cool temperatures (10-25°C), high humidity (>90%), and long periods of leaf wetness. Spreads extremely rapidly by wind-borne spores and water splash. Can destroy entire crop in 1-2 weeks.', '1. Plant resistant varieties if available\r\n2. Avoid planting near potatoes (shares same disease)\r\n3. Ensure excellent air circulation and drainage\r\n4. Avoid overhead irrigation completely\r\n5. Remove and destroy infected plants immediately\r\n6. Preventive fungicide sprays before symptoms appear\r\n7. Monitor weather - spray before rainy periods', 'AGGRESSIVE treatment needed - this is emergency!\r\n1. Ridomil Gold MZ: 50g per 20L water every 7 days\r\n2. Dithane M45 (Mancozeb): 40g per 20L every 5-7 days\r\n3. Acrobat MZ: 40g per 20L water\r\n4. Copper-based fungicides as backup\r\nStart treatment at first sign. Spray entire plant thoroughly.\r\nRemove and burn infected plants. Do NOT compost.\r\nMay need to abandon severely infected fields', 'critical', 'leaves, stems, fruits - entire plant', 'Airborne spores, water splash, can spread kilometers', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(17, 'Newcastle Disease', 'Avian paramyxovirus type 1', 'poultry', 'viral', 'Respiratory distress (gasping, coughing, sneezing). Greenish watery diarrhea. Twisted neck, paralysis, wing drooping. Sudden death. Drop in egg production up to 50%. Soft-shelled eggs. Mortality can reach 100% in unvaccinated flocks.', 'Highly contagious viral disease spread through respiratory secretions, feces, contaminated equipment, wild birds, and human clothing. Virus survives in environment for weeks.', '1. Strict vaccination schedule (Day 7, Day 21, then every 2-3 months)\r\n2. Strong biosecurity: footbaths, limited visitors, all-in all-out system\r\n3. Quarantine new birds for 14 days\r\n4. Clean and disinfect between batches\r\n5. Proper disposal of dead birds\r\n6. Control wild bird access', 'NO CURE - virus is fatal. Supportive care only:\r\n- Broad spectrum antibiotics (Oxytetracycline, Enrofloxacin) prevent secondary bacterial infections\r\n- Multivitamins in water to boost immunity\r\n- Electrolytes to prevent dehydration\r\n- Isolate sick birds immediately\r\n- Report outbreak to authorities', 'critical', 'respiratory system, nervous system, digestive system', 'Airborne, fecal-oral, fomites, wild birds', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(18, 'Infectious Coryza', 'Avibacterium paragallinarum', 'poultry', 'bacterial', 'Watery nasal discharge progressing to thick, foul-smelling mucus. Severe facial swelling around eyes and wattles. Conjunctivitis (red, swollen eyes). Reduced appetite and water intake. Drop in egg production (10-40%). Difficulty breathing.', 'Bacterial infection spread through direct contact with infected birds, contaminated water, equipment. Worsened by poor ventilation, overcrowding, stress, ammonia buildup, and vitamin A deficiency.', '1. Purchase birds from disease-free sources\r\n2. Maintain good ventilation without drafts\r\n3. Avoid overcrowding (proper stocking density)\r\n4. Provide adequate vitamin A in diet\r\n5. Keep litter dry to reduce ammonia\r\n6. Quarantine new birds\r\n7. Consider vaccination in endemic areas', '1. Sulfadimethoxine in drinking water (1g per liter for 3-5 days)\r\n2. Tylosin injection (10-20mg/kg body weight)\r\n3. Erythromycin in feed (200g per ton for 7-14 days)\r\n4. Oxytetracycline (500mg per liter of water)\r\nTreatment duration: Minimum 3-5 days, continue 2 days after symptoms disappear\r\nImprove ventilation and reduce stocking density', 'high', 'respiratory system, face, eyes', 'Direct contact, aerosol, contaminated water and equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(19, 'Fowl Pox', 'Avipoxvirus', 'poultry', 'viral', 'Warty, yellowish nodules on unfeathered parts: comb, wattles, around eyes, beak, legs. Scabs form and fall off after 2-3 weeks. Diphtheritic form: Yellow patches in mouth, throat causing difficulty breathing and eating. Reduced egg production. Slow growth in young birds.', 'Viral disease transmitted by mosquitoes (primary), biting flies, mites. Also spreads through skin abrasions, cannibalism, contaminated equipment. Virus can persist in scabs for months.', '1. Vaccinate all birds at 6-8 weeks of age (wing web stab method)\r\n2. Control mosquitoes: remove standing water, use mosquito nets\r\n3. Control external parasites (mites, lice)\r\n4. Prevent fighting and cannibalism\r\n5. Isolate infected birds\r\n6. Disinfect equipment between flocks', 'NO specific antiviral treatment. Supportive care:\r\n1. Remove scabs carefully, apply iodine or gentian violet\r\n2. Broad spectrum antibiotics prevent secondary bacterial infections\r\n3. Multivitamins and vitamin A supplementation\r\n4. Improve nutrition\r\n5. For diphtheritic form: glycerin or honey in throat\r\nDisease is self-limiting, lasts 2-4 weeks', 'medium', 'skin, mucous membranes, respiratory system', 'Mosquitoes, biting insects, direct contact, contaminated equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(20, 'Coccidiosis', 'Eimeria species', 'poultry', 'pest', 'Bloody or brownish diarrhea (distinctive sign). Ruffled feathers, hunched posture. Reduced feed and water intake. Pale comb and wattles. Huddling near heat source. Slow growth in chicks. Sudden death in severe cases. Dehydration.', 'Caused by Eimeria protozoan parasites that damage intestinal lining. Oocysts shed in feces contaminate litter, water, feed. Worsened by wet litter, poor sanitation, overcrowding. Young birds (2-8 weeks) most susceptible.', '1. Keep litter dry - essential for control\r\n2. Ensure good drainage and ventilation\r\n3. Use coccidiostats in starter feed\r\n4. Avoid overcrowding\r\n5. Regular cleaning of feeders and drinkers\r\n6. Build immunity through controlled exposure\r\n7. Consider vaccination (Coccivac)', 'Anticoccidial medications:\r\n1. Amprolium (Amprol): 1ml per liter of water for 5-7 days\r\n2. Sulfadimidine: 1g per liter for 5-7 days\r\n3. Toltrazuril (Baycox): 7ml per liter for 2 consecutive days\r\n4. Diclazuril\r\nAdd multivitamins (especially K for blood clotting)\r\nRemove wet litter immediately\r\nTreatment must continue full course', 'high', 'intestines', 'Fecal-oral through contaminated litter, water, feed', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(21, 'Gumboro Disease', 'Infectious bursa disease virus (IBDV)', 'poultry', 'viral', 'Sudden onset in 3-6 week old chicks. Ruffled feathers, depression. Trembling, loss of balance. Whitish watery diarrhea, vent pecking. Prostration before death. Rapid spread through flock. High mortality (30-60%). Survivors have weakened immune system.', 'Highly contagious viral disease affecting bursa of Fabricius (immune organ). Spreads through feces, contaminated equipment, feed, water, people. Virus very stable, survives months in environment. Maternal antibodies protect first 2-3 weeks.', '1. Vaccinate: Day 14 and Day 21-28 (two doses essential)\r\n2. Use intermediate or intermediate-plus vaccines\r\n3. All-in, all-out management system\r\n4. Thorough cleaning and disinfection between batches\r\n5. Use virucidal disinfectants (formaldehyde, virkon-S)\r\n6. Footbaths at farm entrance\r\n7. Control rodents and wild birds', 'NO specific cure - virus is fatal. Management:\r\n1. Broad spectrum antibiotics prevent secondary infections\r\n2. Multivitamins and vitamin K in water\r\n3. Electrolytes for dehydration\r\n4. Maintain good husbandry\r\n5. Cull severely affected birds\r\n6. Vaccinate unaffected birds if not done\r\nBirds that recover have lifelong immunosuppression', 'critical', 'bursa of Fabricius (immune organ), digestive system', 'Highly contagious through feces, contaminated fomites, feed, water', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(22, 'Tomato Early Blight', 'Alternaria solani', 'vegetables', 'fungal', 'Brown to black spots on older lower leaves with concentric rings (target-like pattern). Spots enlarge and leaves turn yellow then die. Lesions on stems near soil line. Fruit spots near stem end. Disease progresses upward if not controlled.', 'Fungal disease favored by warm (24-29°C), wet conditions. Spreads through rain splash, irrigation water, wind, contaminated tools. Overwinters in crop debris and soil. Stressed plants more susceptible.', '1. Use disease-free transplants and certified seeds\r\n2. Crop rotation (3 years minimum)\r\n3. Remove and destroy old crop debris\r\n4. Mulch to prevent soil splash\r\n5. Avoid overhead irrigation or irrigate early morning\r\n6. Ensure adequate plant spacing for air circulation\r\n7. Balanced fertilization - avoid excess nitrogen', 'Fungicide program:\r\n1. Mancozeb 80% WP: 40g per 20L water, spray every 7-10 days\r\n2. Copper oxychloride: 50g per 20L water\r\n3. Alternate fungicides to prevent resistance\r\n4. Start preventive sprays 2-3 weeks after transplanting\r\n5. Ensure good coverage, especially lower leaves\r\n6. Remove severely infected leaves\r\nCombined with good cultural practices', 'medium', 'leaves, stems, fruits', 'Water splash, wind, contaminated tools and equipment', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(23, 'Tomato Late Blight', 'Phytophthora infestans', 'vegetables', 'fungal', 'Dark brown to black water-soaked lesions on leaves. White fuzzy fungal growth on underside of leaves (distinctive sign). Brown streaks on stems. Brown firm rot on green and ripe fruits. Entire plant can die within days. Very destructive and fast-spreading.', 'Fungal disease favored by cool temperatures (10-25°C), high humidity (>90%), and long periods of leaf wetness. Spreads extremely rapidly by wind-borne spores and water splash. Can destroy entire crop in 1-2 weeks.', '1. Plant resistant varieties if available\r\n2. Avoid planting near potatoes (shares same disease)\r\n3. Ensure excellent air circulation and drainage\r\n4. Avoid overhead irrigation completely\r\n5. Remove and destroy infected plants immediately\r\n6. Preventive fungicide sprays before symptoms appear\r\n7. Monitor weather - spray before rainy periods', 'AGGRESSIVE treatment needed - this is emergency!\r\n1. Ridomil Gold MZ: 50g per 20L water every 7 days\r\n2. Dithane M45 (Mancozeb): 40g per 20L every 5-7 days\r\n3. Acrobat MZ: 40g per 20L water\r\n4. Copper-based fungicides as backup\r\nStart treatment at first sign. Spray entire plant thoroughly.\r\nRemove and burn infected plants. Do NOT compost.\r\nMay need to abandon severely infected fields', 'critical', 'leaves, stems, fruits - entire plant', 'Airborne spores, water splash, can spread kilometers', NULL, NULL, 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19');

-- --------------------------------------------------------

--
-- Table structure for table `crop_varieties`
--

CREATE TABLE `crop_varieties` (
  `id` int(11) NOT NULL,
  `crop_type` varchar(50) NOT NULL,
  `variety_name` varchar(100) NOT NULL,
  `scientific_name` varchar(200) DEFAULT NULL,
  `description` text NOT NULL,
  `maturity_days` int(11) DEFAULT NULL,
  `yield_per_acre` varchar(100) DEFAULT NULL,
  `characteristics` text DEFAULT NULL,
  `advantages` text DEFAULT NULL,
  `disadvantages` text DEFAULT NULL,
  `soil_requirements` text DEFAULT NULL,
  `climate_requirements` text DEFAULT NULL,
  `seed_rate` varchar(100) DEFAULT NULL,
  `spacing` varchar(100) DEFAULT NULL,
  `water_requirements` varchar(100) DEFAULT NULL,
  `images` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`images`)),
  `language` enum('en','lusoga') DEFAULT 'en',
  `created_by` int(11) DEFAULT NULL,
  `is_published` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `crop_varieties`
--

INSERT INTO `crop_varieties` (`id`, `crop_type`, `variety_name`, `scientific_name`, `description`, `maturity_days`, `yield_per_acre`, `characteristics`, `advantages`, `disadvantages`, `soil_requirements`, `climate_requirements`, `seed_rate`, `spacing`, `water_requirements`, `images`, `language`, `created_by`, `is_published`, `created_at`, `updated_at`) VALUES
(1, 'maize', 'Longe 1H', 'Zea mays', 'An early maturing hybrid maize variety developed for Ugandan conditions. Known for high yields and disease resistance.', 90, '25-30 bags (100kg)', 'White grain, medium-sized cobs, strong stalks resistant to lodging, uniform plant height', '• High yielding variety (up to 30 bags/acre)\n• Early maturity (3 months)\n• Resistant to maize streak virus\n• Good storability\n• Drought tolerant', '• Requires good soil fertility\n• Needs timely planting\n• Susceptible to fall armyworm if not managed', 'Well-drained, fertile soils with pH 5.5-7.5. Responds well to organic manure and fertilizer application', 'Requires 600-800mm rainfall during growing season. Optimal temperature 20-30°C. Suitable for altitudes 1000-1800m', '8-10kg per acre', '75cm x 30cm (inter-row x intra-row)', 'Moderate - requires consistent moisture especially during tasseling and grain filling', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(2, 'maize', 'Longe 5', 'Zea mays', 'Popular open-pollinated maize variety suitable for smallholder farmers. Can save seeds for next season.', 105, '18-22 bags (100kg)', 'White grain, open-pollinated variety, medium plant height, good adaptability', '• Seeds can be saved for next season\n• Lower seed costs\n• Good adaptability to various conditions\n• Affordable for smallholders\n• Fair drought tolerance', '• Lower yields compared to hybrids\n• Longer maturity period\n• Less uniform plants\n• Moderate disease resistance', 'Grows in a wide range of soils. Prefers well-drained loamy soils with pH 5.8-7.0', 'Requires 700-900mm rainfall. Suitable for altitudes 1000-2000m. Temperature range 18-32°C', '10-12kg per acre', '75cm x 25cm', 'Moderate to high - needs adequate water throughout growth', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(3, 'maize', 'NARO Maize Hybrid 2', 'Zea mays', 'Improved hybrid variety developed by NARO with excellent yield potential and pest resistance.', 95, '28-35 bags (100kg)', 'Yellow grain, large cobs, tall sturdy plants, high grain quality', '• Very high yielding potential\n• Good resistance to major diseases\n• Quality grain for both food and feed\n• Strong stalks resistant to lodging\n• Fast drying after harvest', '• Higher seed cost\n• Cannot save seeds\n• Requires good management\n• Needs adequate fertilization', 'Requires fertile, well-drained soils. pH 6.0-7.5. Best with both organic and inorganic fertilizers', 'Rainfall: 700-1000mm. Temperature: 20-28°C. Altitude: 800-1800m above sea level', '8kg per acre', '75cm x 30cm', 'High - needs irrigation in dry spells for maximum yield', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(4, 'beans', 'K132 (NABE 14)', 'Phaseolus vulgaris', 'Popular climbing bean variety with red mottled seeds. High yielding and widely adapted.', 90, '800-1200kg', 'Climbing type, red mottled seeds, vigorous growth, requires staking', '• High yield potential\n• Good market demand\n• Tolerant to low soil fertility\n• Good cooking quality\n• Can be intercropped with maize', '• Requires staking\n• More labor intensive\n• Longer maturity\n• Susceptible to bean fly', 'Grows in most soils. Prefers well-drained loamy soils with pH 5.5-7.0. Moderate fertility requirements', 'Rainfall: 500-1000mm during growing season. Temperature: 15-25°C. Altitude: 1200-2200m', '30-40kg per acre', '50cm x 20cm with stakes', 'Moderate - critical during flowering and pod filling', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(5, 'beans', 'NABE 15 (Yellow Bean)', 'Phaseolus vulgaris', 'Bush type bean with yellow seeds. Early maturing and suitable for lowland areas.', 65, '500-800kg', 'Bush type, yellow seeds, compact growth, early maturity', '• Very early maturity (65 days)\n• No staking required\n• Good for lowland areas\n• Tolerant to high temperatures\n• Good food quality', '• Lower yield compared to climbing types\n• Smaller market compared to red beans\n• Requires good soil fertility', 'Well-drained soils with good organic matter. pH 5.8-7.0. Benefits from compost application', 'Tolerates higher temperatures (up to 32°C). Rainfall: 400-600mm. Altitude: 600-1600m', '35-45kg per acre', '40cm x 20cm', 'Moderate - needs water during pod development', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(6, 'cassava', 'NASE 14', 'Manihot esculenta', 'High yielding cassava variety resistant to cassava mosaic disease. Sweet variety suitable for fresh consumption and processing.', 360, '20-30 tons fresh roots', 'White flesh, sweet variety, good root quality, CMD resistant, vigorous growth', '• Very high yield potential\n• Excellent CMD resistance\n• Good for both food and processing\n• Sweet variety - good taste\n• Long shelf life in ground\n• Drought tolerant once established', '• Long maturity period (12 months)\n• Requires disease-free planting material\n• Susceptible to cassava brown streak disease in some areas', 'Grows in wide range of soils including poor soils. pH 5.0-8.0. Tolerates low fertility but responds to fertilization', 'Rainfall: 600-1500mm annually. Temperature: 20-35°C. Altitude: 0-1500m. Very drought tolerant', '10,000-12,000 stakes per acre', '1m x 1m', 'Low - very drought tolerant. Needs water mainly in first 3 months', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(7, 'cassava', 'NASE 19', 'Manihot esculenta', 'Improved cassava variety with excellent disease resistance and high starch content. Ideal for industrial processing.', 330, '25-35 tons fresh roots', 'White flesh, high starch content, CMD and CBSD resistant, uniform roots', '• High yielding\n• Dual resistance (CMD and CBSD)\n• High starch content\n• Good for industrial processing\n• Can be harvested from 10 months\n• Good root quality', '• Slightly bitter - mainly for processing\n• Requires clean planting material\n• Needs good establishment', 'Tolerates poor soils but yields better in fertile soils. pH 5.5-7.5. Benefits from organic matter', 'Rainfall: 700-1500mm. Temperature: 22-32°C. Altitude: 0-1400m. Moderate drought tolerance', '10,000 stakes per acre', '1m x 1m', 'Low - drought tolerant after establishment', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(8, 'bananas', 'Bogoya (FHIA-17)', 'Musa spp.', 'Improved cooking banana variety resistant to black sigatoka disease. High yielding and early maturing.', 480, '30-40 bunches/year', 'Cooking type, disease resistant, early bearing, large bunches, sweet when ripe', '• Black sigatoka resistant\n• High yielding\n• Early bearing (16 months)\n• Large sweet bunches\n• Good cooking quality\n• Can be eaten when ripe', '• Susceptible to banana bacterial wilt\n• Requires good management\n• Needs clean planting material', 'Deep, well-drained fertile soils. pH 5.5-7.0. High organic matter requirement. Needs mulching', 'Rainfall: 1200-2000mm evenly distributed. Temperature: 20-30°C. Altitude: 1000-1800m', '450-550 suckers per acre', '3m x 3m', 'High - needs consistent moisture. Benefits from mulching', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(9, 'bananas', 'Kibuzi (East African Highland Banana)', 'Musa AAA-EA', 'Traditional highland cooking banana. Popular for matooke. Improved selection with better yields.', 540, '25-35 bunches/year', 'Traditional matooke type, medium bunches, good cooking quality, highland adapted', '• Preferred for matooke\n• Well adapted to highlands\n• Good taste\n• Established market\n• Tolerates cool conditions', '• Susceptible to diseases\n• Longer maturity\n• Requires clean planting material\n• Labor intensive management', 'Deep fertile soils with high organic matter. pH 5.5-6.5. Requires regular mulching and manure', 'Rainfall: 1200-1800mm. Temperature: 18-26°C. Best at altitudes 1200-2000m', '450 suckers per acre', '3m x 3m', 'High - needs consistent moisture throughout the year', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(10, 'vegetables', 'Sukuma Wiki - Collard Greens', 'Brassica oleracea', 'Traditional leafy vegetable. Quick growing and nutritious. Can harvest multiple times.', 45, '5-8 tons leaves', 'Dark green leaves, fast growing, multiple harvests, highly nutritious', '• Very fast growing (45 days)\n• Multiple harvests possible\n• High demand in markets\n• Nutritious (rich in vitamins)\n• Easy to grow\n• Tolerates various conditions', '• Susceptible to pests (aphids, caterpillars)\n• Requires regular watering\n• Short shelf life after harvest', 'Well-drained fertile soils rich in organic matter. pH 6.0-7.0. Needs good nitrogen supply', 'Grows year-round in most areas. Temperature: 15-25°C. Altitude: 0-2200m. Needs cool conditions for best quality', '2-3kg per acre', '45cm x 30cm', 'High - needs regular watering for tender leaves', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(11, 'vegetables', 'Nakati (African Nightshade)', 'Solanum scabrum', 'Indigenous leafy vegetable. Highly nutritious and fast growing. Popular in local markets.', 40, '4-6 tons leaves', 'Indigenous vegetable, dark green leaves, soft texture, rich flavor', '• Very nutritious (iron, calcium, vitamins)\n• Fast growing (40 days)\n• Multiple harvests\n• Drought tolerant\n• Pest resistant\n• High market demand', '• Perishable - short shelf life\n• Needs frequent harvesting\n• Can be weedy if not managed', 'Grows in most soils. Prefers fertile soils with organic matter. pH 5.5-7.0', 'Temperature: 18-28°C. Rainfall: 400-1000mm. Altitude: 500-2000m. Quite adaptable', '1-2kg per acre', '30cm x 20cm', 'Moderate - drought tolerant but produces better with regular watering', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(12, 'coffee', 'Robusta (Nganda)', 'Coffea canephora', 'Traditional robusta coffee variety. Hardy and productive. Well adapted to Uganda conditions.', 1095, '1-2 tons clean coffee/acre/year', 'Robusta type, hardy plants, good bean quality, disease resistant, drought tolerant', '• Hardy and disease resistant\n• Drought tolerant\n• Good yields with proper management\n• Lower management costs\n• Good for organic production\n• Strong coffee flavor', '• Takes 3 years to first harvest\n• Lower price than Arabica\n• Requires processing\n• Biennial bearing pattern', 'Wide range of soils. pH 5.5-6.5. Needs good drainage. Benefits from mulching and organic matter', 'Rainfall: 1200-2000mm. Temperature: 18-28°C. Altitude: 900-1500m. Tolerates higher temperatures', '1,000-1,200 seedlings per acre', '3m x 3m', 'Moderate - drought tolerant but needs water during flowering and berry development', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07'),
(13, 'sugar_cane', 'N14', 'Saccharum officinarum', 'Improved sugar cane variety. High sugar content and good ratooning ability.', 450, '80-120 tons cane/acre', 'High sugar content, good ratooning, disease resistant, erect growth', '• High sugar content (12-14%)\n• Good ratooning (3-4 ratoons)\n• Disease resistant\n• Good juice quality\n• Strong stalks\n• Responds well to fertilization', '• Long maturity (15 months)\n• Requires good soil fertility\n• Labor intensive harvesting\n• Needs large land area', 'Deep, fertile, well-drained soils. pH 6.0-7.5. Heavy feeder - needs fertilization and manure', 'Rainfall: 1200-2000mm well distributed. Temperature: 20-30°C. Altitude: 1000-1500m', '60,000-70,000 setts per acre', '1.5m x 0.6m (double row)', 'High - needs consistent moisture especially during growth phase', NULL, 'en', NULL, 1, '2026-02-02 19:32:07', '2026-02-02 19:32:07');

-- --------------------------------------------------------

--
-- Table structure for table `database_backups`
--

CREATE TABLE `database_backups` (
  `id` int(11) NOT NULL,
  `backup_name` varchar(200) NOT NULL,
  `backup_type` enum('full','incremental','partial') DEFAULT 'full',
  `backup_size` bigint(20) DEFAULT NULL COMMENT 'Size in bytes',
  `backup_path` varchar(500) NOT NULL,
  `backup_status` enum('in_progress','completed','failed','corrupted') DEFAULT 'in_progress',
  `tables_included` text DEFAULT NULL COMMENT 'Comma-separated list',
  `compression_type` varchar(20) DEFAULT 'gzip',
  `encryption_enabled` tinyint(1) DEFAULT 0,
  `created_by` int(11) DEFAULT NULL,
  `scheduled_backup` tinyint(1) DEFAULT 0,
  `retention_days` int(11) DEFAULT 30,
  `error_message` text DEFAULT NULL,
  `started_at` timestamp NULL DEFAULT current_timestamp(),
  `completed_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `database_backups`
--
DELIMITER $$
CREATE TRIGGER `alert_backup_failure` AFTER UPDATE ON `database_backups` FOR EACH ROW BEGIN
    IF NEW.backup_status = 'failed' AND OLD.backup_status != 'failed' THEN
        INSERT INTO system_alerts (
            alert_type, severity, title, message, alert_data
        ) VALUES (
            'backup_failed',
            'critical',
            'Database Backup Failed',
            CONCAT('Backup "', NEW.backup_name, '" failed: ', COALESCE(NEW.error_message, 'Unknown error')),
            JSON_OBJECT('backup_id', NEW.id, 'backup_name', NEW.backup_name, 'error', NEW.error_message)
        );
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `disease_reports`
--

CREATE TABLE `disease_reports` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `disease_id` int(11) DEFAULT NULL,
  `crop_type` varchar(50) NOT NULL,
  `location` varchar(100) DEFAULT NULL,
  `location_lat` decimal(10,8) DEFAULT NULL,
  `location_lng` decimal(11,8) DEFAULT NULL,
  `description` text NOT NULL,
  `images` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`images`)),
  `severity` enum('low','medium','high','critical') DEFAULT 'medium',
  `status` enum('pending','verified','resolved','false_alarm') DEFAULT 'pending',
  `verified_by` int(11) DEFAULT NULL,
  `verified_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `districts`
--

CREATE TABLE `districts` (
  `id` int(11) NOT NULL,
  `region_id` int(11) NOT NULL,
  `district_name` varchar(100) NOT NULL,
  `district_code` varchar(10) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `districts`
--

INSERT INTO `districts` (`id`, `region_id`, `district_name`, `district_code`, `created_at`) VALUES
(1, 1, 'Luuka', 'LUU', '2026-01-26 21:19:04'),
(2, 1, 'Iganga', 'IGA', '2026-01-26 21:19:04'),
(3, 1, 'Jinja', 'JIN', '2026-01-26 21:19:04'),
(4, 1, 'Bugiri', 'BUG', '2026-01-26 21:19:04'),
(5, 1, 'Mayuge', 'MAY', '2026-01-26 21:19:04'),
(6, 1, 'Kamuli', 'KAM', '2026-01-26 21:19:04'),
(7, 1, 'Buyende', 'BUY', '2026-01-26 21:19:04'),
(8, 1, 'Kaliro', 'KAL', '2026-01-26 21:19:04'),
(9, 1, 'Namutumba', 'NAM', '2026-01-26 21:19:04'),
(10, 2, 'Kampala', 'KLA', '2026-01-26 21:19:04'),
(11, 2, 'Wakiso', 'WAK', '2026-01-26 21:19:04'),
(12, 2, 'Mukono', 'MUK', '2026-01-26 21:19:04'),
(13, 2, 'Mpigi', 'MPG', '2026-01-26 21:19:04'),
(14, 3, 'Mbarara', 'MBA', '2026-01-26 21:19:04'),
(15, 3, 'Kasese', 'KAS', '2026-01-26 21:19:04'),
(16, 3, 'Fort Portal', 'FPT', '2026-01-26 21:19:04'),
(17, 3, 'Kabale', 'KBL', '2026-01-26 21:19:04'),
(18, 4, 'Mbale', 'MBL', '2026-01-26 21:19:04'),
(19, 4, 'Soroti', 'SRT', '2026-01-26 21:19:04'),
(20, 4, 'Tororo', 'TRR', '2026-01-26 21:19:04'),
(21, 4, 'Kumi', 'KUM', '2026-01-26 21:19:04'),
(22, 5, 'Gulu', 'GLU', '2026-01-26 21:19:04'),
(23, 5, 'Lira', 'LRA', '2026-01-26 21:19:04'),
(24, 5, 'Arua', 'ARU', '2026-01-26 21:19:04'),
(25, 5, 'Kitgum', 'KTG', '2026-01-26 21:19:04'),
(26, 1, 'BUGWERI', 'BGW', '2026-01-27 20:52:20'),
(27, 1, 'JINJA CITY', 'JNC', '2026-01-27 20:52:20'),
(28, 2, 'BUIKWE', 'BWK', '2026-01-27 20:52:20'),
(29, 2, 'BUTAMBALA', 'BTM', '2026-01-27 20:52:20'),
(30, 2, 'BUVUMA', 'BUV', '2026-01-27 20:52:20'),
(31, 2, 'GOMBA', 'GMB', '2026-01-27 20:52:20'),
(32, 2, 'KALANGALA', 'KLG', '2026-01-27 20:52:20'),
(33, 2, 'KALUNGU', 'KLN', '2026-01-27 20:52:20'),
(34, 2, 'KAYUNGA', 'KYG', '2026-01-27 20:52:20'),
(35, 2, 'KIBOGA', 'KBG', '2026-01-27 20:52:20'),
(36, 2, 'KYANKWANZI', 'KKZ', '2026-01-27 20:52:20'),
(37, 2, 'LUWEERO', 'LWR', '2026-01-27 20:52:20'),
(38, 2, 'LWENGO', 'LWN', '2026-01-27 20:52:20'),
(39, 2, 'LYANTONDE', 'LYT', '2026-01-27 20:52:20'),
(40, 2, 'MASAKA', 'MSK', '2026-01-27 20:52:20'),
(41, 2, 'MASAKA CITY', 'MSC', '2026-01-27 20:52:20'),
(42, 2, 'MITYANA', 'MTY', '2026-01-27 20:52:20'),
(43, 2, 'MUBENDE', 'MBD', '2026-01-27 20:52:20'),
(44, 2, 'NAKASEKE', 'NKS', '2026-01-27 20:52:20'),
(45, 2, 'NAKASONGOLA', 'NKG', '2026-01-27 20:52:20'),
(46, 2, 'RAKAI', 'RKI', '2026-01-27 20:52:20'),
(47, 2, 'SSEMBABULE', 'SSB', '2026-01-27 20:52:20'),
(48, 2, 'KASSANDA', 'KSD', '2026-01-27 20:52:20'),
(49, 2, 'BUKOMANSIMBI', 'BKM', '2026-01-27 20:52:20'),
(50, 2, 'KYOTERA', 'KYT', '2026-01-27 20:52:20'),
(51, 3, 'BUHWEJU', 'BHW', '2026-01-27 20:52:20'),
(52, 3, 'BULIISA', 'BLS', '2026-01-27 20:52:20'),
(53, 3, 'BUNDIBUGYO', 'BDB', '2026-01-27 20:52:20'),
(54, 3, 'BUNYANGABU', 'BYB', '2026-01-27 20:52:20'),
(55, 3, 'BUSHENYI', 'BSH', '2026-01-27 20:52:20'),
(56, 3, 'FORT PORTAL CITY', 'FPC', '2026-01-27 20:52:20'),
(57, 3, 'HOIMA', 'HMA', '2026-01-27 20:52:20'),
(58, 3, 'HOIMA CITY', 'HMC', '2026-01-27 20:52:20'),
(59, 3, 'IBANDA', 'IBD', '2026-01-27 20:52:20'),
(60, 3, 'ISINGIRO', 'ISG', '2026-01-27 20:52:20'),
(61, 3, 'KABAROLE', 'KBR', '2026-01-27 20:52:20'),
(62, 3, 'KAGADI', 'KGD', '2026-01-27 20:52:20'),
(63, 3, 'KAKUMIRO', 'KKM', '2026-01-27 20:52:20'),
(64, 3, 'KAMWENGE', 'KMW', '2026-01-27 20:52:20'),
(65, 3, 'KANUNGU', 'KNN', '2026-01-27 20:52:20'),
(66, 3, 'KAZO', 'KZO', '2026-01-27 20:52:20'),
(67, 3, 'KIBAALE', 'KBL', '2026-01-27 20:52:20'),
(68, 3, 'KIKUUBE', 'KKB', '2026-01-27 20:52:20'),
(69, 3, 'KIRUHURA', 'KRH', '2026-01-27 20:52:20'),
(70, 3, 'KIRYANDONGO', 'KRD', '2026-01-27 20:52:20'),
(71, 3, 'KISORO', 'KSR', '2026-01-27 20:52:20'),
(72, 3, 'KITAGWENDA', 'KTG', '2026-01-27 20:52:20'),
(73, 3, 'KYEGEGWA', 'KYG', '2026-01-27 20:52:20'),
(74, 3, 'KYENJOJO', 'KYJ', '2026-01-27 20:52:20'),
(75, 3, 'MASINDI', 'MSD', '2026-01-27 20:52:20'),
(76, 3, 'MBARARA CITY', 'MBC', '2026-01-27 20:52:20'),
(77, 3, 'MITOOMA', 'MTM', '2026-01-27 20:52:20'),
(78, 3, 'NTOROKO', 'NTK', '2026-01-27 20:52:20'),
(79, 3, 'NTUNGAMO', 'NTG', '2026-01-27 20:52:20'),
(80, 3, 'RUBANDA', 'RBD', '2026-01-27 20:52:20'),
(81, 3, 'RUBIRIZI', 'RBR', '2026-01-27 20:52:20'),
(82, 3, 'RUKIGA', 'RKG', '2026-01-27 20:52:20'),
(83, 3, 'RUKUNGIRI', 'RKN', '2026-01-27 20:52:20'),
(84, 3, 'RWAMPARA', 'RWP', '2026-01-27 20:52:20'),
(85, 3, 'SHEEMA', 'SHM', '2026-01-27 20:52:20'),
(86, 4, 'AMURIA', 'AMR', '2026-01-27 20:52:20'),
(87, 4, 'BUDAKA', 'BDK', '2026-01-27 20:52:20'),
(88, 4, 'BUDUDA', 'BDD', '2026-01-27 20:52:20'),
(89, 4, 'BUKEDEA', 'BKD', '2026-01-27 20:52:20'),
(90, 4, 'BUKWO', 'BKW', '2026-01-27 20:52:20'),
(91, 4, 'BULAMBULI', 'BLB', '2026-01-27 20:52:20'),
(92, 4, 'BUSIA', 'BSA', '2026-01-27 20:52:20'),
(93, 4, 'BUTALEJA', 'BTJ', '2026-01-27 20:52:20'),
(94, 4, 'BUTEBO', 'BTB', '2026-01-27 20:52:20'),
(95, 4, 'KABERAMAIDO', 'KBM', '2026-01-27 20:52:20'),
(96, 4, 'KALAKI', 'KLK', '2026-01-27 20:52:20'),
(97, 4, 'KAPCHORWA', 'KPC', '2026-01-27 20:52:20'),
(98, 4, 'KAPELEBYONG', 'KPB', '2026-01-27 20:52:20'),
(99, 4, 'KATAKWI', 'KTK', '2026-01-27 20:52:20'),
(100, 4, 'KIBUKU', 'KBK', '2026-01-27 20:52:20'),
(101, 4, 'KWEEN', 'KWN', '2026-01-27 20:52:20'),
(102, 4, 'MANAFWA', 'MNF', '2026-01-27 20:52:20'),
(103, 4, 'MBALE CITY', 'MBC', '2026-01-27 20:52:20'),
(104, 4, 'NAMISINDWA', 'NMS', '2026-01-27 20:52:20'),
(105, 4, 'NGORA', 'NGR', '2026-01-27 20:52:20'),
(106, 4, 'PALLISA', 'PLL', '2026-01-27 20:52:20'),
(107, 4, 'SERERE', 'SRR', '2026-01-27 20:52:20'),
(108, 4, 'SIRONKO', 'SRK', '2026-01-27 20:52:20'),
(109, 4, 'SOROTI CITY', 'SRC', '2026-01-27 20:52:20'),
(110, 5, 'ABIM', 'ABM', '2026-01-27 20:52:20'),
(111, 5, 'ADJUMANI', 'ADJ', '2026-01-27 20:52:20'),
(112, 5, 'AGAGO', 'AGG', '2026-01-27 20:52:20'),
(113, 5, 'ALEBTONG', 'ALB', '2026-01-27 20:52:20'),
(114, 5, 'AMOLATAR', 'AML', '2026-01-27 20:52:20'),
(115, 5, 'AMUDAT', 'AMD', '2026-01-27 20:52:20'),
(116, 5, 'AMURU', 'AMU', '2026-01-27 20:52:20'),
(117, 5, 'APAC', 'APC', '2026-01-27 20:52:20'),
(118, 5, 'ARUA CITY', 'ARC', '2026-01-27 20:52:20'),
(119, 5, 'DOKOLO', 'DKL', '2026-01-27 20:52:20'),
(120, 5, 'GULU CITY', 'GLC', '2026-01-27 20:52:20'),
(121, 5, 'KAABONG', 'KAB', '2026-01-27 20:52:20'),
(122, 5, 'KARENGA', 'KRG', '2026-01-27 20:52:20'),
(123, 5, 'KITGUM', 'KTM', '2026-01-27 20:52:20'),
(124, 5, 'KOBOKO', 'KBK', '2026-01-27 20:52:20'),
(125, 5, 'KOLE', 'KLE', '2026-01-27 20:52:20'),
(126, 5, 'KOTIDO', 'KTD', '2026-01-27 20:52:20'),
(127, 5, 'KWANIA', 'KWN', '2026-01-27 20:52:20'),
(128, 5, 'LAMWO', 'LMW', '2026-01-27 20:52:20'),
(129, 5, 'LIRA CITY', 'LRC', '2026-01-27 20:52:20'),
(130, 5, 'MADI-OKOLLO', 'MDO', '2026-01-27 20:52:20'),
(131, 5, 'MARACHA', 'MRC', '2026-01-27 20:52:20'),
(132, 5, 'MOROTO', 'MRT', '2026-01-27 20:52:20'),
(133, 5, 'MOYO', 'MYO', '2026-01-27 20:52:20'),
(134, 5, 'NABILATUK', 'NBL', '2026-01-27 20:52:20'),
(135, 5, 'NAKAPIRIPIRIT', 'NKP', '2026-01-27 20:52:20'),
(136, 5, 'NAPAK', 'NPK', '2026-01-27 20:52:20'),
(137, 5, 'NEBBI', 'NBB', '2026-01-27 20:52:20'),
(138, 5, 'NWOYA', 'NWY', '2026-01-27 20:52:20'),
(139, 5, 'OBONGI', 'OBG', '2026-01-27 20:52:20'),
(140, 5, 'OMORO', 'OMR', '2026-01-27 20:52:20'),
(141, 5, 'OTUKE', 'OTK', '2026-01-27 20:52:20'),
(142, 5, 'OYAM', 'OYM', '2026-01-27 20:52:20'),
(143, 5, 'PADER', 'PDR', '2026-01-27 20:52:20'),
(144, 5, 'PAKWACH', 'PKW', '2026-01-27 20:52:20'),
(145, 5, 'TEREGO', 'TRG', '2026-01-27 20:52:20'),
(146, 5, 'YUMBE', 'YMB', '2026-01-27 20:52:20'),
(147, 5, 'ZOMBO', 'ZMB', '2026-01-27 20:52:20');

-- --------------------------------------------------------

--
-- Table structure for table `email_queue`
--

CREATE TABLE `email_queue` (
  `id` int(11) NOT NULL,
  `to_email` varchar(100) NOT NULL,
  `to_name` varchar(100) DEFAULT NULL,
  `subject` varchar(255) NOT NULL,
  `body_html` text DEFAULT NULL,
  `body_text` text DEFAULT NULL,
  `from_email` varchar(100) DEFAULT NULL,
  `from_name` varchar(100) DEFAULT NULL,
  `reply_to` varchar(100) DEFAULT NULL,
  `cc` text DEFAULT NULL,
  `bcc` text DEFAULT NULL,
  `attachments` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`attachments`)),
  `priority` enum('low','normal','high') DEFAULT 'normal',
  `status` enum('pending','sent','failed','bounced') DEFAULT 'pending',
  `attempts` int(11) DEFAULT 0,
  `max_attempts` int(11) DEFAULT 3,
  `error_message` text DEFAULT NULL,
  `sent_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `encrypted_files`
--

CREATE TABLE `encrypted_files` (
  `id` int(11) NOT NULL,
  `message_id` int(11) DEFAULT NULL,
  `user_id` int(11) NOT NULL,
  `original_filename` varchar(255) NOT NULL,
  `encrypted_filename` varchar(255) NOT NULL,
  `file_size` int(11) NOT NULL,
  `mime_type` varchar(100) DEFAULT NULL,
  `encrypted_key` text NOT NULL,
  `iv` varchar(255) NOT NULL,
  `file_hash` varchar(64) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `encryption_audit_log`
--

CREATE TABLE `encryption_audit_log` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `action_type` enum('key_generated','key_rotated','key_accessed','decrypt_failed','encrypt_failed') NOT NULL,
  `description` text DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `encryption_audit_log`
--

INSERT INTO `encryption_audit_log` (`id`, `user_id`, `action_type`, `description`, `ip_address`, `user_agent`, `created_at`) VALUES
(1, 3, 'key_generated', 'User generated encryption keys', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:22:35'),
(2, 9, 'key_generated', 'User generated encryption keys', '::1', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0', '2026-02-07 06:27:49');

-- --------------------------------------------------------

--
-- Table structure for table `enterprises`
--

CREATE TABLE `enterprises` (
  `id` int(11) NOT NULL,
  `farm_id` int(11) NOT NULL,
  `enterprise_type` enum('sugar_cane','poultry','maize','vegetables','coffee','beans','cassava','bananas','dairy','piggery','other') NOT NULL,
  `enterprise_name` varchar(100) DEFAULT NULL,
  `size_acres` decimal(10,2) DEFAULT 0.00,
  `quantity` int(11) DEFAULT 0,
  `planting_date` date DEFAULT NULL,
  `expected_harvest_date` date DEFAULT NULL,
  `status` enum('planning','planted','growing','harvesting','completed') DEFAULT 'planning',
  `notes` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `enterprises`
--

INSERT INTO `enterprises` (`id`, `farm_id`, `enterprise_type`, `enterprise_name`, `size_acres`, `quantity`, `planting_date`, `expected_harvest_date`, `status`, `notes`, `created_at`, `updated_at`) VALUES
(1, 1, 'sugar_cane', '', 12.00, 0, '2025-06-06', '2026-12-06', 'growing', 'If you are ready with your cash', '2026-02-01 21:51:47', '2026-02-01 21:51:47');

-- --------------------------------------------------------

--
-- Table structure for table `extension_activity_log`
--

CREATE TABLE `extension_activity_log` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `assignment_id` int(11) DEFAULT NULL,
  `activity_type` enum('service_delivery','farmer_visit','training','meeting','report_submission','supervision','other') NOT NULL,
  `activity_description` text NOT NULL,
  `farmers_reached` int(11) DEFAULT 0,
  `location_details` varchar(200) DEFAULT NULL,
  `activity_date` date NOT NULL,
  `duration_hours` decimal(5,2) DEFAULT NULL,
  `status` enum('planned','completed','cancelled') DEFAULT 'completed',
  `notes` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `extension_assignments`
--

CREATE TABLE `extension_assignments` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  `organization_name` varchar(200) DEFAULT NULL COMMENT 'NAADS, MAAIF, specific NGO name',
  `assigned_level` enum('national','regional','district','subcounty','parish','village') NOT NULL,
  `region_id` int(11) DEFAULT NULL,
  `district_id` int(11) DEFAULT NULL,
  `subcounty_id` int(11) DEFAULT NULL,
  `parish_id` int(11) DEFAULT NULL,
  `village_id` int(11) DEFAULT NULL,
  `supervisor_id` int(11) DEFAULT NULL COMMENT 'User ID of supervising extension worker',
  `employee_id` varchar(50) DEFAULT NULL,
  `start_date` date NOT NULL,
  `end_date` date DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `assigned_by` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `extension_assignments`
--

INSERT INTO `extension_assignments` (`id`, `user_id`, `role_id`, `organization_name`, `assigned_level`, `region_id`, `district_id`, `subcounty_id`, `parish_id`, `village_id`, `supervisor_id`, `employee_id`, `start_date`, `end_date`, `is_active`, `assigned_by`, `created_at`, `updated_at`) VALUES
(1, 2, 1, 'MAIF', 'national', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '0000-00-00', NULL, 1, 5, '2026-02-04 18:40:56', '2026-02-04 18:40:56');

-- --------------------------------------------------------

--
-- Table structure for table `extension_officer_profiles`
--

CREATE TABLE `extension_officer_profiles` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `employee_id` varchar(50) DEFAULT NULL,
  `organization` varchar(200) DEFAULT NULL COMMENT 'NAADS, MAAIF, NGO, etc.',
  `qualification` varchar(100) DEFAULT NULL COMMENT 'Diploma, Degree, Masters, etc.',
  `specialization` varchar(100) DEFAULT NULL COMMENT 'Agronomy, Animal Husbandry, etc.',
  `years_of_experience` int(11) DEFAULT 0,
  `areas_of_expertise` text DEFAULT NULL COMMENT 'JSON array of expertise areas',
  `assigned_districts` text DEFAULT NULL COMMENT 'JSON array of district IDs',
  `license_number` varchar(50) DEFAULT NULL,
  `license_expiry` date DEFAULT NULL,
  `qualification_documents` text DEFAULT NULL COMMENT 'JSON array of certificate URLs',
  `is_verified` tinyint(1) DEFAULT 0,
  `verification_date` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `extension_reports`
--

CREATE TABLE `extension_reports` (
  `id` int(11) NOT NULL,
  `submitted_by` int(11) NOT NULL,
  `assignment_id` int(11) NOT NULL,
  `report_type` enum('daily','weekly','monthly','quarterly','annual','special') NOT NULL,
  `report_period_start` date NOT NULL,
  `report_period_end` date NOT NULL,
  `farmers_contacted` int(11) DEFAULT 0,
  `services_delivered` int(11) DEFAULT 0,
  `trainings_conducted` int(11) DEFAULT 0,
  `problems_identified` text DEFAULT NULL,
  `solutions_implemented` text DEFAULT NULL,
  `recommendations` text DEFAULT NULL,
  `report_file_url` varchar(255) DEFAULT NULL,
  `status` enum('draft','submitted','reviewed','approved','rejected') DEFAULT 'draft',
  `reviewed_by` int(11) DEFAULT NULL,
  `review_notes` text DEFAULT NULL,
  `submitted_at` timestamp NULL DEFAULT NULL,
  `reviewed_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `extension_resources`
--

CREATE TABLE `extension_resources` (
  `id` int(11) NOT NULL,
  `created_by` int(11) NOT NULL,
  `resource_type` enum('tip','guide','manual','video','document','presentation') NOT NULL,
  `title` varchar(200) NOT NULL,
  `description` text DEFAULT NULL,
  `content` longtext DEFAULT NULL,
  `file_url` varchar(255) DEFAULT NULL,
  `category` varchar(100) DEFAULT NULL,
  `target_level` enum('all','national','regional','district','subcounty','parish','village') DEFAULT 'all',
  `language` enum('en','lusoga') DEFAULT 'en',
  `is_published` tinyint(1) DEFAULT 0,
  `views_count` int(11) DEFAULT 0,
  `downloads_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `extension_roles`
--

CREATE TABLE `extension_roles` (
  `id` int(11) NOT NULL,
  `role_name` varchar(100) NOT NULL,
  `role_level` enum('national','regional','district','subcounty','parish','village') NOT NULL,
  `role_description` text DEFAULT NULL,
  `organization_type` enum('government','ngo','international','private') DEFAULT 'government',
  `permissions` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`permissions`)),
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `extension_roles`
--

INSERT INTO `extension_roles` (`id`, `role_name`, `role_level`, `role_description`, `organization_type`, `permissions`, `is_active`, `created_at`, `updated_at`) VALUES
(1, 'National Coordinator', 'national', 'Oversees all extension services at national level', 'government', '{\"manage_all\":true,\"view_all_reports\":true,\"assign_regional\":true,\"manage_resources\":true,\"approve_reports\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(2, 'National Extension Officer', 'national', 'Provides technical support at national level', 'government', '{\"view_reports\":true,\"create_resources\":true,\"supervise_regional\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(3, 'Regional Coordinator', 'regional', 'Manages extension services in assigned region', 'government', '{\"manage_region\":true,\"assign_district\":true,\"view_district_reports\":true,\"approve_district_reports\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(4, 'Regional Extension Officer', 'regional', 'Provides services at regional level', 'government', '{\"view_regional_data\":true,\"create_resources\":true,\"supervise_district\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(5, 'District Agricultural Officer', 'district', 'Oversees district agricultural extension', 'government', '{\"manage_district\":true,\"assign_subcounty\":true,\"view_subcounty_reports\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(6, 'District Fisheries Officer', 'district', 'Manages fisheries extension in district', 'government', '{\"manage_fisheries\":true,\"supervise_subcounty\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(7, 'District Livestock Officer', 'district', 'Manages livestock extension in district', 'government', '{\"manage_livestock\":true,\"supervise_subcounty\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(8, 'Subcounty Extension Officer', 'subcounty', 'Provides extension services at subcounty level', 'government', '{\"manage_subcounty\":true,\"assign_parish\":true,\"conduct_training\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(9, 'Parish Extension Worker', 'parish', 'Provides extension services at parish level', 'government', '{\"manage_parish\":true,\"conduct_visits\":true,\"submit_reports\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(10, 'Village Extension Agent', 'village', 'Provides frontline services at village level', 'government', '{\"conduct_visits\":true,\"submit_reports\":true,\"assist_farmers\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(11, 'NGO National Coordinator', 'national', 'NGO extension coordinator at national level', 'ngo', '{\"manage_ngo_programs\":true,\"view_reports\":true,\"create_resources\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23'),
(12, 'NGO Field Officer', 'district', 'NGO field officer at district level', 'ngo', '{\"implement_programs\":true,\"conduct_training\":true,\"submit_reports\":true}', 1, '2026-02-03 12:20:23', '2026-02-03 12:20:23');

-- --------------------------------------------------------

--
-- Table structure for table `extension_services`
--

CREATE TABLE `extension_services` (
  `id` int(11) NOT NULL,
  `officer_id` int(11) NOT NULL,
  `service_type` enum('farm_visit','training','consultation','demonstration') NOT NULL,
  `title` varchar(200) NOT NULL,
  `description` text DEFAULT NULL,
  `location` varchar(100) DEFAULT NULL,
  `scheduled_date` date NOT NULL,
  `scheduled_time` time DEFAULT NULL,
  `duration_hours` int(11) DEFAULT 2,
  `max_participants` int(11) DEFAULT NULL,
  `status` enum('scheduled','ongoing','completed','cancelled') DEFAULT 'scheduled',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `extension_specializations`
--

CREATE TABLE `extension_specializations` (
  `id` int(11) NOT NULL,
  `assignment_id` int(11) NOT NULL,
  `specialization_type` enum('general','crops','livestock','fisheries','poultry','horticulture','soil','irrigation','agribusiness','other') NOT NULL,
  `specialization_name` varchar(200) NOT NULL,
  `is_primary` tinyint(1) DEFAULT 0,
  `certification_details` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `failed_login_attempts`
--

CREATE TABLE `failed_login_attempts` (
  `id` int(11) NOT NULL,
  `phone_number` varchar(15) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `ip_address` varchar(45) NOT NULL,
  `user_agent` text DEFAULT NULL,
  `attempt_count` int(11) DEFAULT 1,
  `is_blocked` tinyint(1) DEFAULT 0,
  `block_expires_at` timestamp NULL DEFAULT NULL,
  `last_attempt` timestamp NULL DEFAULT current_timestamp(),
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `failed_login_attempts`
--
DELIMITER $$
CREATE TRIGGER `auto_block_brute_force` AFTER UPDATE ON `failed_login_attempts` FOR EACH ROW BEGIN
    IF NEW.attempt_count >= 5 AND NEW.is_blocked = 0 THEN
        UPDATE failed_login_attempts 
        SET is_blocked = 1, 
            block_expires_at = DATE_ADD(NOW(), INTERVAL 1 HOUR)
        WHERE id = NEW.id;
        
        INSERT INTO ip_access_control (ip_address, access_type, reason, expires_at)
        VALUES (NEW.ip_address, 'temporary_block', 'Brute force detected', DATE_ADD(NOW(), INTERVAL 1 HOUR))
        ON DUPLICATE KEY UPDATE 
            block_count = block_count + 1,
            expires_at = DATE_ADD(NOW(), INTERVAL 1 HOUR);
        
        INSERT INTO security_threats (
            threat_type, severity, ip_address, action_taken
        ) VALUES (
            'brute_force', 'high', NEW.ip_address, 'blocked'
        );
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `farming_contracts`
--

CREATE TABLE `farming_contracts` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `farmer_id` int(11) NOT NULL,
  `product_type` varchar(100) NOT NULL,
  `quantity_contracted` decimal(10,2) NOT NULL,
  `unit` varchar(20) DEFAULT 'kg',
  `price_per_unit` decimal(10,2) NOT NULL,
  `total_contract_value` decimal(12,2) NOT NULL,
  `quality_specifications` text DEFAULT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `delivery_schedule` text DEFAULT NULL,
  `payment_terms` text DEFAULT NULL,
  `advance_payment` decimal(10,2) DEFAULT 0.00,
  `advance_payment_date` date DEFAULT NULL,
  `contract_document` varchar(255) DEFAULT NULL,
  `status` enum('draft','pending_approval','active','completed','terminated') DEFAULT 'draft',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `farming_contracts`
--
DELIMITER $$
CREATE TRIGGER `update_contract_value` BEFORE INSERT ON `farming_contracts` FOR EACH ROW BEGIN
    SET NEW.total_contract_value = NEW.quantity_contracted * NEW.price_per_unit;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_contract_value_on_update` BEFORE UPDATE ON `farming_contracts` FOR EACH ROW BEGIN
    SET NEW.total_contract_value = NEW.quantity_contracted * NEW.price_per_unit;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `farming_schedules`
--

CREATE TABLE `farming_schedules` (
  `id` int(11) NOT NULL,
  `crop_type` varchar(50) NOT NULL,
  `activity_type` enum('land_preparation','planting','weeding','fertilization','pest_control','irrigation','harvesting','post_harvest') NOT NULL,
  `title` varchar(200) NOT NULL,
  `description` text NOT NULL,
  `timing` varchar(100) DEFAULT NULL COMMENT 'e.g., "2-3 weeks after planting"',
  `week_from_planting` int(11) DEFAULT NULL,
  `duration_days` int(11) DEFAULT NULL,
  `season` enum('first_season','second_season','all_year') DEFAULT 'all_year',
  `instructions` text DEFAULT NULL,
  `materials_needed` text DEFAULT NULL,
  `estimated_cost` decimal(10,2) DEFAULT NULL,
  `priority` enum('low','medium','high','critical') DEFAULT 'medium',
  `language` enum('en','lusoga') DEFAULT 'en',
  `created_by` int(11) DEFAULT NULL,
  `is_published` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `farming_schedules`
--

INSERT INTO `farming_schedules` (`id`, `crop_type`, `activity_type`, `title`, `description`, `timing`, `week_from_planting`, `duration_days`, `season`, `instructions`, `materials_needed`, `estimated_cost`, `priority`, `language`, `created_by`, `is_published`, `created_at`, `updated_at`) VALUES
(1, 'maize', 'land_preparation', 'Land Clearing and Ploughing', 'Clear the land and plough to prepare for planting', '2-3 weeks before planting', -2, 7, 'all_year', '1. Clear all vegetation\n2. Plough to 15-20cm depth\n3. Break large soil clods\n4. Level the field', 'Hoe or plough, Slasher, Rake', 50000.00, 'high', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(2, 'maize', 'planting', 'Maize Planting', 'Plant maize seeds at the start of the rainy season', 'At start of rains', 0, 3, 'first_season', '1. Make holes 75cm x 30cm apart\n2. Plant 2-3 seeds per hole\n3. Cover with 3-5cm of soil\n4. Apply basal fertilizer if available', 'Maize seeds (5-10kg/acre), DAP fertilizer (50kg/acre)', 120000.00, 'critical', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(3, 'maize', 'weeding', 'First Weeding', 'Remove weeds to reduce competition', '2-3 weeks after planting', 2, 2, 'all_year', '1. Remove all weeds carefully\n2. Avoid damaging maize roots\n3. Create small mounds around plants', 'Hoe, Hand weeding', 30000.00, 'high', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(4, 'maize', 'fertilization', 'Top Dressing', 'Apply nitrogen fertilizer for better growth', '4-6 weeks after planting', 5, 1, 'all_year', '1. Apply Urea (50kg/acre)\n2. Place 5cm from plant base\n3. Cover with soil\n4. Ensure soil has moisture', 'Urea fertilizer (50kg/acre)', 80000.00, 'high', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(5, 'maize', 'weeding', 'Second Weeding', 'Final weeding before maturity', '6-8 weeks after planting', 7, 2, 'all_year', '1. Remove all weeds\n2. Earth up around plants\n3. Check for pests and diseases', 'Hoe', 30000.00, 'medium', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(6, 'maize', 'pest_control', 'Pest and Disease Management', 'Monitor and control pests throughout growth', 'Throughout growing season', 3, 60, 'all_year', '1. Scout for pests weekly\n2. Apply pesticides if threshold reached\n3. Use recommended chemicals\n4. Follow safety precautions', 'Insecticides, Sprayer, Protective gear', 50000.00, 'high', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(7, 'maize', 'harvesting', 'Maize Harvesting', 'Harvest when cobs are mature and dry', '3-4 months after planting', 14, 7, 'all_year', '1. Check if kernels are hard\n2. Harvest when husks are brown and dry\n3. Dry cobs to 13-14% moisture\n4. Shell and store properly', 'Bags, Storage facility', 40000.00, 'critical', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(8, 'maize', 'post_harvest', 'Drying and Storage', 'Proper drying and storage to prevent losses', 'Immediately after harvesting', 15, 14, 'all_year', '1. Dry maize to 13-14% moisture\n2. Store in clean, dry place\n3. Use proper storage bags\n4. Apply storage pesticides\n5. Regular monitoring', 'Tarpaulin, Storage bags, Storage pesticides', 60000.00, 'high', 'en', NULL, 1, '2026-02-02 14:52:15', '2026-02-02 14:52:15'),
(9, 'beans', 'land_preparation', 'Land Preparation for Beans', 'Prepare land for bean planting', '1-2 weeks before planting', -1, 5, 'all_year', '1. Clear land of weeds and crop residues\n2. Plough to 15cm depth\n3. Make ridges if soil is heavy\n4. Mix in compost if available', 'Hoe, Rake, Compost (optional)', 30000.00, 'high', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(10, 'beans', 'planting', 'Bean Planting', 'Plant beans at optimal spacing', 'At start of rains', 0, 2, 'first_season', '1. Make holes 20cm apart in rows 50cm apart\n2. Plant 2-3 seeds per hole\n3. Cover with 3-5cm soil\n4. Apply DAP if available (1 teaspoon per hole)', 'Bean seeds (35-40kg/acre), DAP fertilizer (optional)', 80000.00, 'critical', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(11, 'beans', 'weeding', 'First Weeding', 'Remove competing weeds', '2 weeks after planting', 2, 2, 'all_year', '1. Remove all weeds carefully\n2. Slightly earth up around plants\n3. For climbing beans, start setting up stakes', 'Hoe, Stakes (for climbing types)', 25000.00, 'high', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(12, 'beans', 'pest_control', 'Pest and Disease Management', 'Protect beans from pests', '3-6 weeks after planting', 3, 30, 'all_year', '1. Scout for aphids, bean fly weekly\n2. Spray if necessary with approved insecticides\n3. Remove diseased plants\n4. Apply fungicides if rust appears', 'Insecticide, Fungicide, Sprayer', 40000.00, 'high', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(13, 'beans', 'harvesting', 'Bean Harvesting', 'Harvest beans at right maturity', '8-12 weeks after planting', 9, 14, 'all_year', '1. Harvest when pods are dry and brittle\n2. Harvest in dry weather\n3. Dry further on tarpaulin\n4. Shell and clean\n5. Store in dry bags', 'Tarpaulin, Storage bags', 30000.00, 'critical', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(14, 'cassava', 'planting', 'Cassava Planting', 'Plant cassava cuttings', 'Start of rainy season', 0, 7, 'first_season', '1. Select disease-free stakes from healthy plants\n2. Cut into 25cm pieces with 5-7 nodes\n3. Plant at 45-degree angle\n4. Bury 2/3 of stake in soil\n5. Firm soil around stake', 'Cassava stakes (10,000-12,000 per acre)', 150000.00, 'critical', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(15, 'cassava', 'weeding', 'First Weeding', 'Keep field weed-free', '6-8 weeks after planting', 7, 3, 'all_year', '1. Remove all weeds manually or with hoe\n2. Be careful not to damage shallow roots\n3. Create small mounds around plants', 'Hoe', 40000.00, 'high', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(16, 'cassava', 'weeding', 'Second Weeding', 'Final weeding before canopy closes', '12-14 weeks after planting', 13, 3, 'all_year', '1. Remove all remaining weeds\n2. Earth up around plants\n3. After this, canopy will suppress most weeds', 'Hoe', 35000.00, 'medium', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(17, 'cassava', 'harvesting', 'Cassava Harvesting', 'Harvest mature cassava', '10-12 months after planting', 45, 60, 'all_year', '1. Can start harvesting from 10 months for NASE varieties\n2. Cut stem 30cm above ground\n3. Loosen soil around plant\n4. Pull out roots carefully\n5. Process within 2-3 days', 'Hoe, Panga, Transport', 80000.00, 'critical', 'en', NULL, 1, '2026-02-02 19:33:51', '2026-02-02 19:33:51'),
(18, 'poultry', 'planting', 'Brooding Day-Old Layer Chicks', 'Setting up brooder and receiving day-old layer chicks. Critical first week for survival.', 'Day 1', 0, 7, 'all_year', '1. Heat brooder to 32-35°C before chicks arrive\r\n2. Use heat lamp or charcoal stove\r\n3. Provide chick feed in flat trays first 3 days\r\n4. Shallow water in chick drinkers (prevent drowning)\r\n5. Keep continuous light first 2 days\r\n6. Check chicks every 2 hours - adjust temperature by observing behavior\r\n7. Space: 50 chicks per square meter\r\n8. Sprinkle vitamin-electrolyte in water', 'Heat source, thermometer, chick feeders, chick drinkers, newspapers, saw dust, chick starter feed, vitamins', 30000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(19, 'poultry', 'fertilization', 'Week 1 Vaccination - Newcastle & IB', 'First vaccination against Newcastle Disease and Infectious Bronchitis to establish immunity.', 'Week 1 (Day 7)', 1, 1, 'all_year', '1. Use ND LaSota or ND B1 vaccine\r\n2. Combine with IB H120 vaccine\r\n3. Administer through eye drop or drinking water\r\n4. Eye drop more effective for small numbers\r\n5. For water vaccination: withhold water 2 hours, add vaccine to cool water, provide for 2 hours\r\n6. Add 2-3% skimmed milk powder to water to protect vaccine\r\n7. Ensure all birds drink\r\n8. Watch for mild reactions (sneezing, watery eyes) - normal', 'ND vaccine, IB vaccine, cool clean water, skimmed milk powder, eye droppers', 10000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(20, 'poultry', 'fertilization', 'Week 3 & 5 - Gumboro Vaccination', 'Gumboro (IBD) vaccination to protect immune system. Two doses needed.', 'Week 3 and Week 5', 3, 1, 'all_year', '1. Use intermediate or intermediate-plus Gumboro vaccine\r\n2. First dose at Day 14\r\n3. Booster dose at Day 21-28\r\n4. Administer through drinking water\r\n5. Withdraw water 1-2 hours before vaccination\r\n6. Use cool, chlorine-free water\r\n7. Add vaccine and allow birds to drink within 1-2 hours\r\n8. Add skimmed milk to stabilize vaccine\r\n9. Both doses are essential for full protection', 'Gumboro vaccine (intermediate strength), cool water, skimmed milk powder', 15000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(21, 'poultry', 'fertilization', 'Week 8 - Fowl Pox Vaccination', 'Fowl pox vaccination using wing web stab method for long-lasting immunity.', 'Week 8', 8, 1, 'all_year', '1. Use fowl pox vaccine\r\n2. Wing web stab method (most effective)\r\n3. Stretch wing, find web between wing bones\r\n4. Dip double-needle applicator in reconstituted vaccine\r\n5. Stab through wing web once\r\n6. Check for \"take\" after 7-10 days - small scab at vaccination site indicates success\r\n7. Revaccinate birds with no take\r\n8. One vaccination gives lifetime immunity', 'Fowl pox vaccine, double-needle applicator, methylated spirit for disinfection', 12000.00, 'high', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(22, 'poultry', 'fertilization', 'Week 16 and Every 3 Months - Newcastle Booster', 'Regular Newcastle Disease booster vaccinations to maintain immunity throughout productive life.', 'Week 16, then every 12 weeks', 16, 1, 'all_year', '1. Use ND LaSota vaccine\r\n2. Administer through drinking water or spray\r\n3. Spray method: fine spray in enclosed area, 30ml vaccine per 1000 birds\r\n4. Water method: same as week 1 procedure\r\n5. Keep vaccination records with dates\r\n6. Never skip booster - disease can be devastating\r\n7. Vaccinate before periods of stress (extreme weather, moving birds)', 'ND LaSota vaccine, spray equipment or clean water, skimmed milk', 8000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(23, 'poultry', 'harvesting', 'Point of Lay - First Eggs', 'Managing pullets as they start laying eggs. Critical nutrition and management period.', 'Week 18-20', 18, 14, 'all_year', '1. Switch to layer mash (17-18% protein, 3.5-4% calcium)\r\n2. Ensure 14-16 hours light daily\r\n3. Provide oyster shells separately for extra calcium\r\n4. Ensure adequate nest boxes (1 per 4-5 birds)\r\n5. Collect eggs frequently to prevent egg eating habit\r\n6. First eggs will be small - normal\r\n7. Production increases gradually to 50% by week 24\r\n8. Maintain clean, dry nesting material\r\n9. Never disturb birds in nests', 'Layer mash, oyster shells, nest box material (saw dust or rice husks), extra feeders and drinkers', 50000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(24, 'poultry', 'planting', 'Brooding Day-Old Broiler Chicks', 'Intensive brooding of broiler chicks. Higher temperature needed than layers.', 'Day 1', 0, 7, 'all_year', '1. Pre-heat brooder to 32-35°C (higher than layers)\r\n2. Broilers are more heat-sensitive - monitor closely\r\n3. Provide broiler starter feed ad lib from day 1\r\n4. Use chick drinkers, prevent drowning\r\n5. 24 hour light first 3 days to encourage feeding\r\n6. Space: 40-50 chicks per square meter initially\r\n7. Reduce temperature by 2-3°C weekly\r\n8. Vitamin-electrolyte in water first 3 days reduces stress mortality', 'Heat source, thermometer, feeders, drinkers, bedding, broiler starter feed, vitamins', 35000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(25, 'poultry', 'fertilization', 'Week 1 - Broiler Vaccination', 'Minimal vaccination for broilers due to short production cycle.', 'Week 1 (Day 7-10)', 1, 1, 'all_year', '1. ND + IB combination vaccine\r\n2. Eye drop or spray method\r\n3. Some farmers skip vaccination (risky but common)\r\n4. In high disease areas, vaccination recommended\r\n5. Gumboro at Day 14 if disease present in area\r\n6. No other vaccines needed due to short cycle (6 weeks)', 'ND+IB vaccine, eye droppers', 8000.00, 'high', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(26, 'poultry', 'fertilization', 'Week 3 - Switch to Grower Feed', 'Transition from starter to grower feed for optimal growth.', 'Week 3 (Day 21)', 3, 2, 'all_year', '1. Gradually switch from starter to grower over 3-4 days\r\n2. Mix feeds: Day 1: 75% starter + 25% grower, Day 2: 50-50, Day 3: 25-75, Day 4: 100% grower\r\n3. Grower has lower protein (20-21%) but higher energy\r\n4. Monitor feed consumption - should eat 90-130g per day\r\n5. Ensure continuous access to feed\r\n6. Check for any respiratory issues', 'Broiler grower feed', 200000.00, 'high', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19'),
(27, 'poultry', 'harvesting', 'Week 6 - Market Ready', 'Harvesting broilers at optimal market weight of 2.0-2.5kg.', 'Week 6 (Day 42)', 6, 2, 'all_year', '1. Target weight: 2.0-2.5kg live weight\r\n2. Withdraw feed 8-12 hours before slaughter\r\n3. Water can continue until slaughter\r\n4. Transport early morning or evening (cooler)\r\n5. Rough handling reduces meat quality - be gentle\r\n6. Can extend to Week 7 (2.8-3.0kg) if market demands\r\n7. Never keep beyond Week 8 - feed conversion worsens', 'Transport crates, scales', 50000.00, 'critical', 'en', NULL, 1, '2026-02-03 09:44:19', '2026-02-03 09:44:19');

-- --------------------------------------------------------

--
-- Table structure for table `farms`
--

CREATE TABLE `farms` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `farm_name` varchar(100) DEFAULT NULL,
  `total_acres` decimal(10,2) DEFAULT 0.00,
  `location_lat` decimal(10,8) DEFAULT NULL,
  `location_lng` decimal(11,8) DEFAULT NULL,
  `soil_type` varchar(50) DEFAULT NULL,
  `water_source` varchar(100) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `farms`
--

INSERT INTO `farms` (`id`, `user_id`, `farm_name`, `total_acres`, `location_lat`, `location_lng`, `soil_type`, `water_source`, `created_at`, `updated_at`) VALUES
(1, 3, 'Ebenezar Agro Farm', 40.00, 0.34078700, 32.59105300, 'Mixed', 'Multiple Sources', '2026-01-30 07:02:04', '2026-02-02 19:55:17'),
(2, 9, 'My Farm', 0.00, NULL, NULL, '', '', '2026-01-31 13:25:01', '2026-01-31 13:25:01');

-- --------------------------------------------------------

--
-- Table structure for table `favorites`
--

CREATE TABLE `favorites` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `friendships`
--

CREATE TABLE `friendships` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `friend_id` int(11) NOT NULL,
  `status` enum('pending','accepted','blocked') DEFAULT 'pending',
  `requested_at` timestamp NULL DEFAULT current_timestamp(),
  `accepted_at` timestamp NULL DEFAULT NULL
) ;

--
-- Dumping data for table `friendships`
--

INSERT INTO `friendships` (`id`, `user_id`, `friend_id`, `status`, `requested_at`, `accepted_at`) VALUES
(1, 3, 9, 'accepted', '2026-01-31 13:18:14', '2026-01-31 13:20:21'),
(2, 9, 4, 'pending', '2026-01-31 13:21:33', NULL),
(3, 9, 2, 'accepted', '2026-01-31 13:21:38', '2026-02-03 14:34:02'),
(4, 9, 5, 'pending', '2026-01-31 13:21:41', NULL),
(5, 4, 3, 'pending', '2026-02-07 06:44:14', NULL);

--
-- Triggers `friendships`
--
DELIMITER $$
CREATE TRIGGER `notify_friend_request` AFTER INSERT ON `friendships` FOR EACH ROW BEGIN
    IF NEW.status = 'pending' THEN
        INSERT INTO notifications (user_id, title, message, type, icon, link)
        SELECT 
            NEW.friend_id,
            'New Friend Request',
            CONCAT((SELECT full_name FROM users WHERE id = NEW.user_id), ' sent you a friend request'),
            'info',
            'person-plus',
            '/friends/requests.php'
        FROM DUAL;
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `friend_suggestions`
--

CREATE TABLE `friend_suggestions` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `suggested_user_id` int(11) NOT NULL,
  `suggestion_reason` varchar(100) DEFAULT NULL,
  `mutual_friends_count` int(11) DEFAULT 0,
  `is_dismissed` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `groups`
--

CREATE TABLE `groups` (
  `id` int(11) NOT NULL,
  `group_name` varchar(100) NOT NULL,
  `description` text DEFAULT NULL,
  `group_avatar` varchar(255) DEFAULT NULL,
  `group_cover` varchar(255) DEFAULT NULL,
  `privacy` enum('public','private','secret') DEFAULT 'public',
  `created_by` int(11) NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `location` varchar(100) DEFAULT NULL,
  `rules` text DEFAULT NULL,
  `member_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `groups`
--

INSERT INTO `groups` (`id`, `group_name`, `description`, `group_avatar`, `group_cover`, `privacy`, `created_by`, `category`, `location`, `rules`, `member_count`, `created_at`, `updated_at`) VALUES
(1, 'Poultry Fermers', 'About Poultry', NULL, NULL, 'public', 3, 'poultry', NULL, '', 1, '2026-01-31 09:59:21', '2026-01-31 09:59:21'),
(2, 'Tomatoe Farmers Group Bulongo', 'All bout Tomatoes', 'assets/uploads/groups/697e0ca651167_images.jpg', NULL, 'public', 9, 'vegetables', NULL, 'Always Stick to the group Norms', 1, '2026-01-31 14:07:34', '2026-01-31 14:07:35');

-- --------------------------------------------------------

--
-- Table structure for table `group_events`
--

CREATE TABLE `group_events` (
  `id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  `created_by` int(11) NOT NULL,
  `event_name` varchar(200) NOT NULL,
  `description` text DEFAULT NULL,
  `event_date` datetime NOT NULL,
  `location` varchar(200) DEFAULT NULL,
  `event_type` enum('online','in_person','hybrid') DEFAULT 'in_person',
  `max_attendees` int(11) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `group_members`
--

CREATE TABLE `group_members` (
  `id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `role` enum('admin','moderator','member') DEFAULT 'member',
  `status` enum('active','pending','blocked') DEFAULT 'active',
  `joined_at` timestamp NULL DEFAULT current_timestamp(),
  `invited_by` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `group_members`
--

INSERT INTO `group_members` (`id`, `group_id`, `user_id`, `role`, `status`, `joined_at`, `invited_by`) VALUES
(1, 1, 3, 'admin', 'active', '2026-01-31 09:59:21', NULL),
(2, 2, 9, 'admin', 'active', '2026-01-31 14:07:35', NULL);

--
-- Triggers `group_members`
--
DELIMITER $$
CREATE TRIGGER `update_group_member_count_delete` AFTER DELETE ON `group_members` FOR EACH ROW BEGIN
    IF OLD.status = 'active' THEN
        UPDATE groups SET member_count = member_count - 1 WHERE id = OLD.group_id;
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_group_member_count_insert` AFTER INSERT ON `group_members` FOR EACH ROW BEGIN
    IF NEW.status = 'active' THEN
        UPDATE groups SET member_count = member_count + 1 WHERE id = NEW.group_id;
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `group_posts`
--

CREATE TABLE `group_posts` (
  `id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `content` text NOT NULL,
  `media_urls` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`media_urls`)),
  `post_type` enum('text','image','poll','event','announcement') DEFAULT 'text',
  `is_pinned` tinyint(1) DEFAULT 0,
  `likes_count` int(11) DEFAULT 0,
  `comments_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `group_post_comments`
--

CREATE TABLE `group_post_comments` (
  `id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `parent_comment_id` int(11) DEFAULT NULL,
  `content` text NOT NULL,
  `likes_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `group_post_likes`
--

CREATE TABLE `group_post_likes` (
  `id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `group_post_likes`
--
DELIMITER $$
CREATE TRIGGER `decrease_group_post_likes_count` AFTER DELETE ON `group_post_likes` FOR EACH ROW BEGIN
    UPDATE group_posts SET likes_count = likes_count - 1 WHERE id = OLD.post_id;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_group_post_likes_count` AFTER INSERT ON `group_post_likes` FOR EACH ROW BEGIN
    UPDATE group_posts SET likes_count = likes_count + 1 WHERE id = NEW.post_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `ip_access_control`
--

CREATE TABLE `ip_access_control` (
  `id` int(11) NOT NULL,
  `ip_address` varchar(45) NOT NULL,
  `access_type` enum('blacklist','whitelist','temporary_block') NOT NULL DEFAULT 'blacklist',
  `reason` text NOT NULL,
  `blocked_by` int(11) DEFAULT NULL,
  `expires_at` timestamp NULL DEFAULT NULL COMMENT 'For temporary blocks',
  `is_active` tinyint(1) DEFAULT 1,
  `block_count` int(11) DEFAULT 1,
  `last_attempt` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `learning_progress`
--

CREATE TABLE `learning_progress` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `content_type` enum('tip','disease','schedule','variety','video','resource') NOT NULL,
  `content_id` int(11) NOT NULL,
  `status` enum('viewed','bookmarked','completed','in_progress') DEFAULT 'viewed',
  `progress_percentage` int(11) DEFAULT 0,
  `time_spent_seconds` int(11) DEFAULT 0,
  `notes` text DEFAULT NULL,
  `rating` int(11) DEFAULT NULL CHECK (`rating` between 1 and 5),
  `is_useful` tinyint(1) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `learning_progress`
--

INSERT INTO `learning_progress` (`id`, `user_id`, `content_type`, `content_id`, `status`, `progress_percentage`, `time_spent_seconds`, `notes`, `rating`, `is_useful`, `created_at`, `updated_at`) VALUES
(1, 3, 'schedule', 3, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 15:05:23', '2026-02-02 15:05:23'),
(2, 3, 'schedule', 1, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 15:05:45', '2026-02-02 15:05:45'),
(3, 3, 'disease', 1, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 15:06:17', '2026-02-02 15:06:17'),
(4, 3, 'disease', 2, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 15:06:31', '2026-02-02 15:06:31'),
(5, 3, 'disease', 4, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 15:06:38', '2026-02-02 15:06:38'),
(6, 3, 'variety', 8, 'viewed', 0, 0, NULL, NULL, NULL, '2026-02-02 19:35:32', '2026-02-02 19:35:32');

-- --------------------------------------------------------

--
-- Table structure for table `markets`
--

CREATE TABLE `markets` (
  `id` int(11) NOT NULL,
  `market_name` varchar(100) NOT NULL,
  `location` varchar(100) NOT NULL,
  `district` varchar(50) DEFAULT NULL,
  `subcounty` varchar(50) DEFAULT NULL,
  `market_days` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of market operation days' CHECK (json_valid(`market_days`)),
  `latitude` decimal(10,8) DEFAULT NULL,
  `longitude` decimal(11,8) DEFAULT NULL,
  `contact_phone` varchar(15) DEFAULT NULL,
  `facilities` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Available facilities' CHECK (json_valid(`facilities`)),
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `markets`
--

INSERT INTO `markets` (`id`, `market_name`, `location`, `district`, `subcounty`, `market_days`, `latitude`, `longitude`, `contact_phone`, `facilities`, `is_active`, `created_at`, `updated_at`) VALUES
(1, 'Luuka Central Market', 'Luuka Town', 'Luuka', 'Luuka Town Council', '[\"Monday\", \"Thursday\", \"Saturday\"]', NULL, NULL, NULL, NULL, 1, '2026-02-02 20:18:34', '2026-02-02 20:18:34'),
(2, 'Irongo Market', 'Irongo', 'Luuka', 'Irongo', '[\"Tuesday\", \"Friday\"]', NULL, NULL, NULL, NULL, 1, '2026-02-02 20:18:34', '2026-02-02 20:18:34'),
(3, 'Nawampiti Market', 'Nawampiti', 'Luuka', 'Nawampiti', '[\"Wednesday\", \"Saturday\"]', NULL, NULL, NULL, NULL, 1, '2026-02-02 20:18:34', '2026-02-02 20:18:34'),
(4, 'Bukooma Market', 'Bukooma', 'Luuka', 'Bukooma', '[\"Monday\", \"Thursday\"]', NULL, NULL, NULL, NULL, 1, '2026-02-02 20:18:34', '2026-02-02 20:18:34');

-- --------------------------------------------------------

--
-- Table structure for table `market_prices`
--

CREATE TABLE `market_prices` (
  `id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `market_location` varchar(100) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `unit` varchar(20) NOT NULL,
  `source` varchar(100) DEFAULT 'Manual Entry',
  `price_date` date NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `market_prices`
--

INSERT INTO `market_prices` (`id`, `product_type`, `market_location`, `price`, `unit`, `source`, `price_date`, `created_at`, `updated_at`) VALUES
(1, 'Sugar Cane', 'Kakira Sugar - Direct', 180000.00, 'ton', 'Direct Contact', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(2, 'Sugar Cane', 'Mayuge Sugar - Direct', 175000.00, 'ton', 'Direct Contact', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(3, 'Sugar Cane', 'Local Middlemen', 120000.00, 'ton', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(4, 'Eggs', 'Luuka Town', 12000.00, 'tray', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(5, 'Chicken', 'Luuka Market', 15000.00, 'bird', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(6, 'Tomatoes', 'Kampala Market', 3500.00, 'kg', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(7, 'Cabbages', 'Iganga Market', 1500.00, 'piece', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(8, 'Maize', 'Luuka Market', 1800.00, 'kg', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(9, 'Beans', 'Jinja Market', 4000.00, 'kg', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(10, 'Coffee', 'Jinja Coffee Mill', 8500.00, 'kg', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(11, 'Bananas', 'Iganga Market', 25000.00, 'bunch', 'Market Survey', '2026-01-25', '2026-01-25 12:45:24', '2026-01-25 12:45:24'),
(12, 'maize', 'Luuka Central Market', 3500.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(13, 'maize', 'Luuka Central Market', 3400.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(14, 'maize', 'Luuka Central Market', 3600.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(15, 'maize', 'Luuka Central Market', 3450.00, 'kg', 'Market Survey', '2026-01-30', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(16, 'maize', 'Luuka Central Market', 3550.00, 'kg', 'Market Survey', '2026-01-26', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(17, 'maize', 'Irongo Market', 3300.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(18, 'maize', 'Irongo Market', 3250.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(19, 'maize', 'Irongo Market', 3350.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(20, 'maize', 'Nawampiti Market', 3700.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(21, 'maize', 'Nawampiti Market', 3650.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(22, 'maize', 'Bukooma Market', 3400.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(23, 'maize', 'Bukooma Market', 3380.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(24, 'sugar_cane', 'Luuka Central Market', 250000.00, 'ton', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(25, 'sugar_cane', 'Luuka Central Market', 245000.00, 'ton', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(26, 'sugar_cane', 'Luuka Central Market', 248000.00, 'ton', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(27, 'sugar_cane', 'Luuka Central Market', 252000.00, 'ton', 'Market Survey', '2026-01-26', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(28, 'sugar_cane', 'Irongo Market', 240000.00, 'ton', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(29, 'sugar_cane', 'Irongo Market', 238000.00, 'ton', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(30, 'sugar_cane', 'Nawampiti Market', 255000.00, 'ton', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(31, 'sugar_cane', 'Nawampiti Market', 253000.00, 'ton', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(32, 'vegetables', 'Luuka Central Market', 2000.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(33, 'vegetables', 'Luuka Central Market', 1950.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(34, 'vegetables', 'Luuka Central Market', 2100.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(35, 'vegetables', 'Irongo Market', 1800.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(36, 'vegetables', 'Irongo Market', 1850.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(37, 'vegetables', 'Nawampiti Market', 2200.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(38, 'vegetables', 'Nawampiti Market', 2150.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(39, 'poultry', 'Luuka Central Market', 18000.00, 'bird', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(40, 'poultry', 'Luuka Central Market', 17500.00, 'bird', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(41, 'poultry', 'Luuka Central Market', 18500.00, 'bird', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(42, 'poultry', 'Irongo Market', 17000.00, 'bird', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(43, 'poultry', 'Irongo Market', 16800.00, 'bird', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(44, 'poultry', 'Nawampiti Market', 19000.00, 'bird', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(45, 'poultry', 'Nawampiti Market', 18800.00, 'bird', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(46, 'beans', 'Luuka Central Market', 4500.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(47, 'beans', 'Luuka Central Market', 4400.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(48, 'beans', 'Luuka Central Market', 4600.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(49, 'beans', 'Irongo Market', 4200.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(50, 'beans', 'Irongo Market', 4150.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(51, 'beans', 'Nawampiti Market', 4700.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(52, 'beans', 'Nawampiti Market', 4650.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(53, 'coffee', 'Luuka Central Market', 8500.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(54, 'coffee', 'Luuka Central Market', 8400.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(55, 'coffee', 'Luuka Central Market', 8600.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(56, 'coffee', 'Irongo Market', 8200.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(57, 'coffee', 'Irongo Market', 8100.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(58, 'coffee', 'Nawampiti Market', 8800.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(59, 'coffee', 'Nawampiti Market', 8750.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(60, 'cassava', 'Luuka Central Market', 1500.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(61, 'cassava', 'Luuka Central Market', 1450.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(62, 'cassava', 'Luuka Central Market', 1550.00, 'kg', 'Market Survey', '2026-01-31', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(63, 'cassava', 'Irongo Market', 1400.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(64, 'cassava', 'Irongo Market', 1380.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(65, 'cassava', 'Nawampiti Market', 1600.00, 'kg', 'Market Survey', '2026-02-02', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(66, 'cassava', 'Nawampiti Market', 1580.00, 'kg', 'Market Survey', '2026-02-01', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(67, 'maize', 'Luuka Central Market', 3500.00, 'kg', 'Market Survey', '2026-01-23', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(68, 'maize', 'Luuka Central Market', 3480.00, 'kg', 'Market Survey', '2026-01-19', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(69, 'maize', 'Luuka Central Market', 3520.00, 'kg', 'Market Survey', '2026-01-12', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(70, 'maize', 'Luuka Central Market', 3550.00, 'kg', 'Market Survey', '2026-01-05', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(71, 'sugar_cane', 'Luuka Central Market', 250000.00, 'ton', 'Market Survey', '2026-01-23', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(72, 'sugar_cane', 'Luuka Central Market', 248000.00, 'ton', 'Market Survey', '2026-01-19', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(73, 'sugar_cane', 'Luuka Central Market', 252000.00, 'ton', 'Market Survey', '2026-01-12', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(74, 'sugar_cane', 'Luuka Central Market', 255000.00, 'ton', 'Market Survey', '2026-01-05', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(75, 'vegetables', 'Luuka Central Market', 2000.00, 'kg', 'Market Survey', '2026-01-23', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(76, 'vegetables', 'Luuka Central Market', 1980.00, 'kg', 'Market Survey', '2026-01-19', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(77, 'vegetables', 'Luuka Central Market', 2050.00, 'kg', 'Market Survey', '2026-01-12', '2026-02-02 20:38:30', '2026-02-02 20:38:30'),
(78, 'vegetables', 'Luuka Central Market', 2100.00, 'kg', 'Market Survey', '2026-01-05', '2026-02-02 20:38:30', '2026-02-02 20:38:30');

--
-- Triggers `market_prices`
--
DELIMITER $$
CREATE TRIGGER `after_price_insert` AFTER INSERT ON `market_prices` FOR EACH ROW BEGIN
    DECLARE prev_price DECIMAL(10,2);
    DECLARE price_change DECIMAL(10,2);
    DECLARE percent_change DECIMAL(5,2);
    
    -- Get previous price for same product/location
    SELECT price INTO prev_price
    FROM market_prices
    WHERE product_type = NEW.product_type
    AND market_location = NEW.market_location
    AND price_date < NEW.price_date
    ORDER BY price_date DESC
    LIMIT 1;
    
    IF prev_price IS NOT NULL THEN
        SET price_change = NEW.price - prev_price;
        SET percent_change = (price_change / prev_price) * 100;
    END IF;
    
    -- Insert into history
    INSERT INTO price_history (
        product_type, market_location, price, unit, source, 
        price_date, change_from_previous, percent_change
    ) VALUES (
        NEW.product_type, NEW.market_location, NEW.price, NEW.unit, 
        NEW.source, NEW.price_date, price_change, percent_change
    );
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `messages`
--

CREATE TABLE `messages` (
  `id` int(11) NOT NULL,
  `chat_id` int(11) NOT NULL,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  `message_type` enum('text','image','document','audio','system') DEFAULT 'text',
  `content` text NOT NULL,
  `encrypted_content` text DEFAULT NULL,
  `media_url` varchar(255) DEFAULT NULL,
  `is_system_message` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `encrypted_key` text DEFAULT NULL,
  `iv` varchar(255) DEFAULT NULL,
  `message_hash` varchar(64) DEFAULT NULL,
  `sender_signature` text DEFAULT NULL,
  `is_encrypted` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `messages`
--

INSERT INTO `messages` (`id`, `chat_id`, `sender_id`, `receiver_id`, `message_type`, `content`, `encrypted_content`, `media_url`, `is_system_message`, `created_at`, `updated_at`, `encrypted_key`, `iv`, `message_hash`, `sender_signature`, `is_encrypted`) VALUES
(1, 1, 3, 2, 'text', 'hello', NULL, '', 0, '2026-02-06 06:51:10', '2026-02-06 07:13:03', NULL, NULL, NULL, NULL, 0),
(2, 1, 3, 2, 'text', 'Good evening', NULL, '', 0, '2026-02-06 17:16:54', '2026-02-06 17:16:54', NULL, NULL, NULL, NULL, 0),
(3, 1, 3, 9, 'text', 'How are you dear', NULL, '', 0, '2026-02-06 17:45:48', '2026-02-06 17:45:48', NULL, NULL, NULL, NULL, 0),
(4, 1, 9, 3, 'text', 'Am fine dear How are you', NULL, '', 0, '2026-02-06 17:47:28', '2026-02-06 17:47:28', NULL, NULL, NULL, NULL, 0),
(5, 1, 3, 9, 'text', 'Am also Fine', NULL, '', 0, '2026-02-06 17:48:20', '2026-02-06 17:48:20', NULL, NULL, NULL, NULL, 0),
(6, 1, 3, 9, 'text', 'Good morning dear', NULL, '', 0, '2026-02-07 06:23:09', '2026-02-07 06:23:09', NULL, NULL, NULL, NULL, 0),
(7, 1, 3, 9, 'text', 'Yes dear how are you', NULL, '', 0, '2026-02-07 06:25:03', '2026-02-07 06:25:03', NULL, NULL, NULL, NULL, 0);

--
-- Triggers `messages`
--
DELIMITER $$
CREATE TRIGGER `check_encryption_keys_before_message` BEFORE INSERT ON `messages` FOR EACH ROW BEGIN
    IF NEW.is_encrypted = 1 THEN
        IF NOT EXISTS (SELECT 1 FROM user_encryption_keys WHERE user_id = NEW.sender_id) THEN
            SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Sender does not have encryption keys generated';
        END IF;
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `prevent_blocked_user_message` BEFORE INSERT ON `messages` FOR EACH ROW BEGIN
    DECLARE is_blocked INT;
    
    -- Check if sender is blocked by any chat member
    SELECT COUNT(*) INTO is_blocked
    FROM chat_members cm
    INNER JOIN user_blocks ub ON (
        (ub.blocker_id = cm.user_id AND ub.blocked_id = NEW.sender_id) OR
        (ub.blocker_id = NEW.sender_id AND ub.blocked_id = cm.user_id)
    )
    WHERE cm.chat_id = NEW.chat_id;
    
    IF is_blocked > 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Cannot send message to blocked user';
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `set_receiver_id_before_insert` BEFORE INSERT ON `messages` FOR EACH ROW BEGIN
    DECLARE chat_type_val VARCHAR(20);
    DECLARE recipient_id INT;
    
    -- Get chat type
    SELECT chat_type INTO chat_type_val 
    FROM chats 
    WHERE id = NEW.chat_id;
    
    -- If one-to-one chat and receiver_id not set, find the other member
    IF chat_type_val = 'one_to_one' AND NEW.receiver_id IS NULL THEN
        SELECT user_id INTO recipient_id
        FROM chat_members
        WHERE chat_id = NEW.chat_id 
        AND user_id != NEW.sender_id
        LIMIT 1;
        
        IF recipient_id IS NOT NULL THEN
            SET NEW.receiver_id = recipient_id;
        ELSE
            SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Cannot determine receiver for one-to-one chat';
        END IF;
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_chat_timestamp` AFTER INSERT ON `messages` FOR EACH ROW BEGIN
    UPDATE chats SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.chat_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `message_attachments`
--

CREATE TABLE `message_attachments` (
  `id` int(11) NOT NULL,
  `message_id` int(11) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `file_type` varchar(50) NOT NULL,
  `file_size` int(11) NOT NULL,
  `file_url` varchar(255) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `message_reactions`
--

CREATE TABLE `message_reactions` (
  `id` int(11) NOT NULL,
  `message_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `reaction` varchar(10) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `message_reports`
--

CREATE TABLE `message_reports` (
  `id` int(11) NOT NULL,
  `reporter_id` int(11) NOT NULL,
  `message_id` int(11) NOT NULL,
  `report_type` enum('spam','harassment','inappropriate','scam','other') NOT NULL,
  `description` text DEFAULT NULL,
  `status` enum('pending','reviewing','resolved','dismissed') DEFAULT 'pending',
  `admin_notes` text DEFAULT NULL,
  `reviewed_by` int(11) DEFAULT NULL,
  `reviewed_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `network_usage`
--

CREATE TABLE `network_usage` (
  `id` int(11) NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `endpoint` varchar(255) NOT NULL,
  `request_method` varchar(10) DEFAULT 'GET',
  `request_size` bigint(20) DEFAULT 0 COMMENT 'Bytes',
  `response_size` bigint(20) DEFAULT 0 COMMENT 'Bytes',
  `response_time` int(11) DEFAULT NULL COMMENT 'Milliseconds',
  `status_code` int(11) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `recorded_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `notifications`
--

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `message` text NOT NULL,
  `type` enum('info','success','warning','danger') DEFAULT 'info',
  `icon` varchar(50) DEFAULT 'bell',
  `link` varchar(255) DEFAULT NULL,
  `is_read` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `notifications`
--

INSERT INTO `notifications` (`id`, `user_id`, `title`, `message`, `type`, `icon`, `link`, `is_read`, `created_at`) VALUES
(1, 9, 'New Friend Request', 'Musumba Jonathan sent you a friend request', 'info', 'person-plus', '/friends/requests.php', 1, '2026-01-31 13:18:14'),
(2, 9, 'New Friend Request', 'You have a new friend request', 'info', 'bell', '/friends/requests.php', 1, '2026-01-31 13:18:14'),
(3, 4, 'New Friend Request', 'Sembera Christopher sent you a friend request', 'info', 'person-plus', '/friends/requests.php', 1, '2026-01-31 13:21:33'),
(4, 4, 'New Friend Request', 'You have a new friend request', 'info', 'bell', '/friends/requests.php', 1, '2026-01-31 13:21:33'),
(5, 2, 'New Friend Request', 'Sembera Christopher sent you a friend request', 'info', 'person-plus', '/friends/requests.php', 1, '2026-01-31 13:21:38'),
(6, 2, 'New Friend Request', 'You have a new friend request', 'info', 'bell', '/friends/requests.php', 0, '2026-01-31 13:21:38'),
(7, 5, 'New Friend Request', 'Sembera Christopher sent you a friend request', 'info', 'person-plus', '/friends/requests.php', 1, '2026-01-31 13:21:41'),
(8, 5, 'New Friend Request', 'You have a new friend request', 'info', 'bell', '/friends/requests.php', 0, '2026-01-31 13:21:41'),
(9, 2, 'New Message', 'Musumba Jonathan sent you a message', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 0, '2026-02-06 06:51:10'),
(10, 2, 'New Message', 'Musumba Jonathan: Good evening', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 0, '2026-02-06 17:16:54'),
(11, 9, 'New Message', 'Musumba Jonathan: How are you dear', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 1, '2026-02-06 17:45:48'),
(12, 3, 'New Message', 'Sembera Christopher: Am fine dear How are you', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 1, '2026-02-06 17:47:28'),
(13, 9, 'New Message', 'Musumba Jonathan: Am also Fine', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 1, '2026-02-06 17:48:20'),
(14, 9, 'New Message', 'Musumba Jonathan: Good morning dear', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 0, '2026-02-07 06:23:09'),
(15, 9, 'New Message', 'Musumba Jonathan: Yes dear how are you', 'info', 'chat', '/chat/one-on-one.php?chat_id=1', 0, '2026-02-07 06:25:03'),
(16, 3, 'New Friend Request', 'Mukisa Emmanuel sent you a friend request', 'info', 'person-plus', '/friends/requests.php', 0, '2026-02-07 06:44:14'),
(17, 3, 'New Friend Request', 'You have a new friend request', 'info', 'bell', '/friends/index.php', 0, '2026-02-07 06:44:14');

--
-- Triggers `notifications`
--
DELIMITER $$
CREATE TRIGGER `after_notification_insert` AFTER INSERT ON `notifications` FOR EACH ROW BEGIN
    -- This is just a flag - actual push sending happens in PHP
    -- You could insert into a queue table here for async processing
    INSERT INTO push_queue (user_id, notification_id, status)
    VALUES (NEW.user_id, NEW.id, 'pending')
    ON DUPLICATE KEY UPDATE status = 'pending';
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `order_number` varchar(20) NOT NULL,
  `product_id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `seller_id` int(11) NOT NULL,
  `quantity` decimal(10,2) NOT NULL,
  `unit_price` decimal(10,2) NOT NULL,
  `total_amount` decimal(10,2) NOT NULL,
  `delivery_address` text DEFAULT NULL,
  `status` enum('pending','confirmed','processing','completed','cancelled') DEFAULT 'pending',
  `payment_status` enum('unpaid','partial','paid') DEFAULT 'unpaid',
  `payment_method` varchar(50) DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `orders`
--
DELIMITER $$
CREATE TRIGGER `notify_new_order` AFTER INSERT ON `orders` FOR EACH ROW BEGIN
    -- Notify seller
    INSERT INTO notifications (user_id, title, message, type, icon, link)
    VALUES (
        NEW.seller_id,
        'New Order Received',
        CONCAT('You have a new order #', NEW.order_number),
        'success',
        'shopping-cart',
        CONCAT('/orders/view.php?id=', NEW.id)
    );
    
    -- Notify buyer
    INSERT INTO notifications (user_id, title, message, type, icon, link)
    VALUES (
        NEW.buyer_id,
        'Order Placed Successfully',
        CONCAT('Your order #', NEW.order_number, ' has been placed'),
        'success',
        'check-circle',
        CONCAT('/orders/view.php?id=', NEW.id)
    );
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `otp_verifications`
--

CREATE TABLE `otp_verifications` (
  `id` int(11) NOT NULL,
  `phone_number` varchar(15) NOT NULL,
  `otp_code` varchar(6) NOT NULL,
  `purpose` enum('registration','login','password_reset') DEFAULT 'registration',
  `is_verified` tinyint(1) DEFAULT 0,
  `expires_at` timestamp NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `otp_verifications`
--

INSERT INTO `otp_verifications` (`id`, `phone_number`, `otp_code`, `purpose`, `is_verified`, `expires_at`, `created_at`) VALUES
(1, '+256777115678', '039750', 'registration', 0, '2026-01-25 16:12:18', '2026-01-25 16:02:18'),
(2, '+256777115678', '768421', 'registration', 1, '2026-01-25 16:28:49', '2026-01-25 16:18:49'),
(3, '+256758697337', '366137', 'registration', 1, '2026-01-26 21:57:56', '2026-01-26 21:47:56'),
(4, '+256777978697', '786412', 'registration', 1, '2026-01-27 08:20:51', '2026-01-27 08:10:51');

-- --------------------------------------------------------

--
-- Table structure for table `parishes`
--

CREATE TABLE `parishes` (
  `id` int(11) NOT NULL,
  `subcounty_id` int(11) NOT NULL,
  `parish_name` varchar(100) NOT NULL,
  `parish_code` varchar(10) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `parishes`
--

INSERT INTO `parishes` (`id`, `subcounty_id`, `parish_name`, `parish_code`, `created_at`) VALUES
(10, 5, 'Busonga Ward', 'BUSONGA', '2026-01-26 21:45:27'),
(11, 9, 'BUGONO', 'BGN', '2026-01-27 20:52:20'),
(12, 9, 'ITANDA', 'ITD', '2026-01-27 20:52:20'),
(13, 9, 'KABIRA-ITUBA', 'KBT', '2026-01-27 20:52:20'),
(14, 9, 'KASAMBIKA', 'KSM', '2026-01-27 20:52:20'),
(15, 9, 'NABITENDE', 'NBT', '2026-01-27 20:52:20'),
(16, 9, 'NALUKO', 'NLK', '2026-01-27 20:52:20'),
(17, 10, 'MWIRA', 'MWR', '2026-01-27 20:52:20'),
(18, 10, 'NAMBALE', 'NMB', '2026-01-27 20:52:20'),
(19, 10, 'NASUTI', 'NST', '2026-01-27 20:52:20'),
(20, 11, 'NAMUNKESU WARD', 'NMK', '2026-01-27 20:52:20'),
(21, 11, 'NAMUNSAALA WARD', 'NMS', '2026-01-27 20:52:20'),
(22, 11, 'NAWANSEGA WARD', 'NWS', '2026-01-27 20:52:20'),
(23, 11, 'BULUMWAKI WARD', 'BLW', '2026-01-27 20:52:20'),
(24, 11, 'MWENDANFUKO WARD', 'MWF', '2026-01-27 20:52:20'),
(25, 11, 'NAMUNGALWE WARD', 'NMG', '2026-01-27 20:52:20'),
(26, 11, 'NAMUNKANAGA WARD', 'NMN', '2026-01-27 20:52:20'),
(27, 12, 'NAWANGAIZA', 'NWG', '2026-01-27 20:52:20'),
(28, 12, 'NAMUSIISI', 'NMS', '2026-01-27 20:52:20'),
(29, 12, 'KYENDABAWALA', 'KYB', '2026-01-27 20:52:20'),
(30, 12, 'KIWANYI', 'KWY', '2026-01-27 20:52:20'),
(31, 12, 'BUGONGO', 'BGG', '2026-01-27 20:52:20'),
(32, 13, 'NAIBIRI', 'NBR', '2026-01-27 20:52:20'),
(33, 13, 'KIDAAGO', 'KDG', '2026-01-27 20:52:20'),
(34, 13, 'KAZIGO', 'KZG', '2026-01-27 20:52:20'),
(35, 13, 'NABITENDE', 'NBT', '2026-01-27 20:52:20'),
(36, 14, 'BUKOYO', 'BKY', '2026-01-27 20:52:20'),
(37, 14, 'BULAMAGI', 'BLG', '2026-01-27 20:52:20'),
(38, 14, 'BULOWOOZA', 'BLW', '2026-01-27 20:52:20'),
(39, 14, 'BWANALIRA', 'BWN', '2026-01-27 20:52:20'),
(40, 14, 'IWAWU', 'IWW', '2026-01-27 20:52:20'),
(41, 15, 'BUKAYE', 'BKY', '2026-01-27 20:52:20'),
(42, 15, 'BUKOONA', 'BKN', '2026-01-27 20:52:20'),
(43, 15, 'BUSEYI', 'BSY', '2026-01-27 20:52:20'),
(44, 15, 'NAKALAMA', 'NKL', '2026-01-27 20:52:20'),
(45, 16, 'BULUBANDI', 'BLB', '2026-01-27 20:52:20'),
(46, 16, 'BUNYAMA', 'BNY', '2026-01-27 20:52:20'),
(47, 16, 'BUSOWOOBI', 'BSW', '2026-01-27 20:52:20'),
(48, 16, 'KABIRA', 'KBR', '2026-01-27 20:52:20'),
(49, 16, 'WAIRAMA', 'WRM', '2026-01-27 20:52:20'),
(50, 17, 'BUNYIRO', 'BNY', '2026-01-27 20:52:20'),
(51, 17, 'MAGOGO', 'MGG', '2026-01-27 20:52:20'),
(52, 17, 'NAWANYINGI', 'NWY', '2026-01-27 20:52:20'),
(53, 18, 'NAKAVULE WARD', 'NKV', '2026-01-27 20:52:20'),
(54, 18, 'NABIDONGHA PRISON WARD', 'NBP', '2026-01-27 20:52:20'),
(55, 18, 'NABIDONGHA WARD', 'NBD', '2026-01-27 20:52:20'),
(56, 18, 'WALUGOGO WARD', 'WLG', '2026-01-27 20:52:20'),
(57, 18, 'KASOKOSO WARD', 'KSK', '2026-01-27 20:52:20'),
(58, 18, 'BULIGO WARD', 'BLG', '2026-01-27 20:52:20'),
(59, 19, 'NKONO WARD', 'NKN', '2026-01-27 20:52:20'),
(60, 19, 'IGAMBA WARD', 'IGB', '2026-01-27 20:52:20'),
(61, 19, 'MUTUKULA WARD', 'MTK', '2026-01-27 20:52:20'),
(62, 19, 'NKATU WARD', 'NKT', '2026-01-27 20:52:20'),
(63, 19, 'BUGUMBA WARD', 'BGM', '2026-01-27 20:52:20'),
(64, 20, 'BUGOBYA', 'BGY', '2026-01-27 20:52:20'),
(65, 20, 'ITAKAIBOLU', 'ITK', '2026-01-27 20:52:20'),
(66, 20, 'KISASI', 'KSS', '2026-01-27 20:52:20'),
(67, 20, 'NABITAMBALA', 'NBT', '2026-01-27 20:52:20'),
(68, 20, 'NALINAIBI', 'NLN', '2026-01-27 20:52:20'),
(69, 21, 'KAKIRA WARD', 'KKR', '2026-01-27 20:52:20'),
(70, 21, 'KARONGO WARD', 'KRG', '2026-01-27 20:52:20'),
(71, 21, 'MAWOITO WARD', 'MWT', '2026-01-27 20:52:20'),
(72, 21, 'WAIRAKA WARD', 'WRK', '2026-01-27 20:52:20'),
(73, 21, 'CHICO WARD', 'CHC', '2026-01-27 20:52:20'),
(74, 21, 'KABYAZA WARD', 'KBZ', '2026-01-27 20:52:20'),
(75, 21, 'MWIRI WARD', 'MWR', '2026-01-27 20:52:20'),
(76, 21, 'POLOTA WARD', 'PLT', '2026-01-27 20:52:20'),
(77, 22, 'BUDIMA', 'BDM', '2026-01-27 20:52:20'),
(78, 22, 'NAKAKULWE (KISOZI)', 'NKK', '2026-01-27 20:52:20'),
(79, 22, 'NAWAMPANDA', 'NWP', '2026-01-27 20:52:20'),
(80, 22, 'WANSIIMBA', 'WNS', '2026-01-27 20:52:20'),
(81, 23, 'NAMAGERA WARD', 'NMG', '2026-01-27 20:52:20'),
(82, 23, 'LUBANI WARD', 'LBN', '2026-01-27 20:52:20'),
(83, 23, 'MPUMWIRE WARD', 'MPM', '2026-01-27 20:52:20'),
(84, 23, 'NAMWENDWA WARD', 'NMW', '2026-01-27 20:52:20'),
(85, 24, 'BUWEERA', 'BWR', '2026-01-27 20:52:20'),
(86, 24, 'KAGOMA', 'KGM', '2026-01-27 20:52:20'),
(87, 24, 'KAIIRA', 'KIR', '2026-01-27 20:52:20'),
(88, 24, 'KITANABA', 'KTN', '2026-01-27 20:52:20'),
(89, 24, 'MAGAMAGA', 'MGM', '2026-01-27 20:52:20'),
(90, 25, 'BULUGO WARD', 'BLG', '2026-01-27 20:52:20'),
(91, 25, 'BUTAMIRA WARD', 'BTM', '2026-01-27 20:52:20'),
(92, 25, 'BUWABUZI WARD', 'BWB', '2026-01-27 20:52:20'),
(93, 25, 'IZIRU WARD', 'IZR', '2026-01-27 20:52:20'),
(94, 26, 'KALITUNSI WARD', 'KLT', '2026-01-27 20:52:20'),
(95, 26, 'KAGAIRE WARD', 'KGR', '2026-01-27 20:52:20'),
(96, 26, 'KASALINA WARD', 'KSL', '2026-01-27 20:52:20'),
(97, 26, 'KAMWANI WARD', 'KMW', '2026-01-27 20:52:20'),
(98, 2, 'Budondo', 'BUD', '2026-01-27 22:06:36'),
(99, 2, 'Buwologoma', 'BWL', '2026-01-27 22:06:36'),
(100, 2, 'Kiroba', 'KRB', '2026-01-27 22:06:36'),
(101, 2, 'Nabubya', 'NBY', '2026-01-27 22:06:36'),
(102, 2, 'Namukubembe', 'NMK', '2026-01-27 22:06:36'),
(103, 27, 'Budhabangula', 'BDH', '2026-01-27 22:06:36'),
(104, 27, 'Bugonyoka', 'BGN', '2026-01-27 22:06:36'),
(105, 27, 'Bukendi', 'BKD', '2026-01-27 22:06:36'),
(106, 27, 'Bulongo', 'BLO', '2026-01-27 22:06:36'),
(107, 27, 'Nakabugu', 'NKB', '2026-01-27 22:06:36'),
(108, 27, 'Namalemba', 'NML', '2026-01-27 22:06:36'),
(109, 3, 'Bunafu', 'BNF', '2026-01-27 22:06:36'),
(110, 3, 'Ikumbya', 'IKM', '2026-01-27 22:06:36'),
(111, 3, 'Inuula', 'INU', '2026-01-27 22:06:36'),
(112, 3, 'Nawaka', 'NWK', '2026-01-27 22:06:36'),
(113, 3, 'Ntayigirwa', 'NTY', '2026-01-27 22:06:36'),
(114, 5, 'Busimawu Ward', 'BSM', '2026-01-27 22:06:36'),
(115, 5, 'Busonga Ward', 'BSG', '2026-01-27 22:06:36'),
(116, 5, 'Kitwekyambogo Ward', 'KTW', '2026-01-27 22:06:36'),
(117, 5, 'Kiyunga Ward', 'KYG', '2026-01-27 22:06:36'),
(118, 5, 'Lwada Ward', 'LWD', '2026-01-27 22:06:36'),
(119, 32, 'Bulanga Ward', 'BLW', '2026-01-27 22:06:36'),
(120, 32, 'Itwe Ward', 'ITW', '2026-01-27 22:06:36'),
(121, 32, 'Mawundo Ward', 'MWD', '2026-01-27 22:06:36'),
(122, 32, 'Nantamu Ward', 'NTM', '2026-01-27 22:06:36'),
(123, 32, 'Walibo Ward', 'WLB', '2026-01-27 22:06:36'),
(124, 30, 'Busalamu East', 'BSE', '2026-01-27 22:06:36'),
(125, 30, 'Busalamu North', 'BSN', '2026-01-27 22:06:36'),
(126, 30, 'Busalamu South', 'BSS', '2026-01-27 22:06:36'),
(127, 30, 'Busalamu West', 'BSW', '2026-01-27 22:06:36'),
(128, 7, 'Irongo', 'IRG', '2026-01-27 22:06:36'),
(129, 7, 'Kalyowa', 'KLW', '2026-01-27 22:06:36'),
(130, 7, 'Kibinga', 'KBG', '2026-01-27 22:06:36'),
(131, 7, 'Kyanvuma', 'KYV', '2026-01-27 22:06:36'),
(132, 7, 'Nawanyago', 'NWG', '2026-01-27 22:06:36'),
(133, 33, 'Buniko Ward', 'BNK', '2026-01-27 22:06:36'),
(134, 33, 'Magada Ward', 'MGD', '2026-01-27 22:06:36'),
(135, 33, 'Nakabaale Ward', 'NKB', '2026-01-27 22:06:36'),
(136, 33, 'Nakabambwe Ward', 'NKM', '2026-01-27 22:06:36'),
(137, 33, 'Nsimakatono Ward', 'NSM', '2026-01-27 22:06:36'),
(138, 6, 'Bugomba', 'BGM', '2026-01-27 22:06:36'),
(139, 6, 'Buyoola', 'BYL', '2026-01-27 22:06:36'),
(140, 6, 'Nakiswiga', 'NKS', '2026-01-27 22:06:36'),
(141, 6, 'Nawampiti', 'NWP', '2026-01-27 22:06:36'),
(142, 6, 'Nawankompe', 'NWK', '2026-01-27 22:06:36'),
(143, 31, 'Busiiro', 'BSR', '2026-01-27 22:06:36'),
(144, 31, 'Butimbwa', 'BTM', '2026-01-27 22:06:36'),
(145, 31, 'Itakaibolu', 'ITK', '2026-01-27 22:06:36'),
(146, 31, 'Lwaki', 'LWK', '2026-01-27 22:06:36'),
(147, 28, 'Bukoma', 'BKM', '2026-01-27 22:06:36'),
(148, 28, 'Bukyangwa', 'BKY', '2026-01-27 22:06:36'),
(149, 28, 'Naigobya', 'NGY', '2026-01-27 22:06:36'),
(150, 28, 'Namansenda', 'NMS', '2026-01-27 22:06:36'),
(151, 28, 'Namulanda', 'NML', '2026-01-27 22:06:36'),
(152, 29, 'Bukhana Ward', 'BKH', '2026-01-27 22:06:36'),
(153, 29, 'Bukoova Central', 'BKC', '2026-01-27 22:06:36'),
(154, 29, 'Bukoova Rural', 'BKR', '2026-01-27 22:06:36'),
(155, 29, 'Bunabala Ward', 'BNB', '2026-01-27 22:06:36'),
(156, 29, 'Busanda Ward', 'BSD', '2026-01-27 22:06:36'),
(157, 29, 'Butaserwa Ward', 'BTS', '2026-01-27 22:06:36'),
(158, 29, 'Buyoga Ward', 'BYG', '2026-01-27 22:06:36'),
(159, 29, 'Makkutu Ward', 'MKT', '2026-01-27 22:06:36'),
(160, 29, 'Nabyoto Ward', 'NBY', '2026-01-27 22:06:36'),
(161, 29, 'Nawansega Ward', 'NWS', '2026-01-27 22:06:36');

-- --------------------------------------------------------

--
-- Table structure for table `photo_comments`
--

CREATE TABLE `photo_comments` (
  `id` int(11) NOT NULL,
  `photo_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `comment_text` text NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `photo_comments`
--
DELIMITER $$
CREATE TRIGGER `update_photo_comments_count` AFTER INSERT ON `photo_comments` FOR EACH ROW BEGIN
    UPDATE profile_photos 
    SET comments_count = comments_count + 1 
    WHERE id = NEW.photo_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `photo_likes`
--

CREATE TABLE `photo_likes` (
  `id` int(11) NOT NULL,
  `photo_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `photo_likes`
--
DELIMITER $$
CREATE TRIGGER `update_photo_likes_count` AFTER INSERT ON `photo_likes` FOR EACH ROW BEGIN
    UPDATE profile_photos 
    SET likes_count = likes_count + 1 
    WHERE id = NEW.photo_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `posts`
--

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `content` text NOT NULL,
  `media_urls` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`media_urls`)),
  `post_type` enum('text','image','video','poll','tip') DEFAULT 'text',
  `visibility` enum('public','friends','private') DEFAULT 'public',
  `location` varchar(100) DEFAULT NULL,
  `likes_count` int(11) DEFAULT 0,
  `comments_count` int(11) DEFAULT 0,
  `shares_count` int(11) DEFAULT 0,
  `is_pinned` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`id`, `user_id`, `content`, `media_urls`, `post_type`, `visibility`, `location`, `likes_count`, `comments_count`, `shares_count`, `is_pinned`, `created_at`, `updated_at`) VALUES
(1, 9, 'Hello Farmers', '[\"http:\\/\\/localhost\\/aims\\/assets\\/uploads\\/posts\\/post_697fca45dea76_1769982533.jpeg\"]', 'image', 'public', NULL, 2, 2, 0, 0, '2026-02-01 21:48:53', '2026-02-02 16:18:42'),
(2, 9, 'New Sugar Factory set up in Buyende District\r\nThe Kidera Sugar factory is now the new kid on the block,Sugar cane is paid cash', NULL, 'text', 'public', NULL, 1, 0, 0, 0, '2026-02-06 17:53:02', '2026-02-06 18:54:13');

-- --------------------------------------------------------

--
-- Table structure for table `post_comments`
--

CREATE TABLE `post_comments` (
  `id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `parent_comment_id` int(11) DEFAULT NULL,
  `content` text NOT NULL,
  `likes_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `post_comments`
--

INSERT INTO `post_comments` (`id`, `post_id`, `user_id`, `parent_comment_id`, `content`, `likes_count`, `created_at`, `updated_at`) VALUES
(1, 1, 3, NULL, 'hi', 0, '2026-02-02 16:09:41', '2026-02-02 16:09:41'),
(2, 1, 3, NULL, 'Yes dear', 0, '2026-02-02 16:18:42', '2026-02-02 16:18:42');

--
-- Triggers `post_comments`
--
DELIMITER $$
CREATE TRIGGER `decrease_post_comments_count` AFTER DELETE ON `post_comments` FOR EACH ROW BEGIN
    UPDATE posts SET comments_count = comments_count - 1 WHERE id = OLD.post_id;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_post_comments_count` AFTER INSERT ON `post_comments` FOR EACH ROW BEGIN
    UPDATE posts SET comments_count = comments_count + 1 WHERE id = NEW.post_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `post_likes`
--

CREATE TABLE `post_likes` (
  `id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `post_likes`
--

INSERT INTO `post_likes` (`id`, `post_id`, `user_id`, `created_at`) VALUES
(1, 1, 9, '2026-02-01 21:49:07'),
(2, 1, 3, '2026-02-02 16:18:29'),
(3, 2, 9, '2026-02-06 18:54:13');

--
-- Triggers `post_likes`
--
DELIMITER $$
CREATE TRIGGER `decrease_post_likes_count` AFTER DELETE ON `post_likes` FOR EACH ROW BEGIN
    UPDATE posts SET likes_count = likes_count - 1 WHERE id = OLD.post_id;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `update_post_likes_count` AFTER INSERT ON `post_likes` FOR EACH ROW BEGIN
    UPDATE posts SET likes_count = likes_count + 1 WHERE id = NEW.post_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `price_alerts`
--

CREATE TABLE `price_alerts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `target_price` decimal(10,2) NOT NULL,
  `alert_condition` enum('above','below') NOT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `last_triggered` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `price_alert_notifications`
--

CREATE TABLE `price_alert_notifications` (
  `id` int(11) NOT NULL,
  `alert_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `trigger_price` decimal(10,2) NOT NULL,
  `target_price` decimal(10,2) NOT NULL,
  `market_location` varchar(100) DEFAULT NULL,
  `notification_sent` tinyint(1) DEFAULT 0,
  `notification_method` enum('push','sms','email') DEFAULT 'push',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `price_comparison_searches`
--

CREATE TABLE `price_comparison_searches` (
  `id` int(11) NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `product_type` varchar(50) NOT NULL,
  `locations_searched` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`locations_searched`)),
  `search_filters` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`search_filters`)),
  `results_count` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `price_history`
--

CREATE TABLE `price_history` (
  `id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `market_location` varchar(100) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `unit` varchar(20) NOT NULL,
  `source` varchar(100) DEFAULT 'Manual Entry',
  `price_date` date NOT NULL,
  `change_from_previous` decimal(10,2) DEFAULT NULL,
  `percent_change` decimal(5,2) DEFAULT NULL,
  `recorded_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `price_history`
--

INSERT INTO `price_history` (`id`, `product_type`, `market_location`, `price`, `unit`, `source`, `price_date`, `change_from_previous`, `percent_change`, `recorded_at`) VALUES
(1, 'maize', 'Luuka Central Market', 3500.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(2, 'maize', 'Luuka Central Market', 3400.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(3, 'maize', 'Luuka Central Market', 3600.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(4, 'maize', 'Luuka Central Market', 3450.00, 'kg', 'Market Survey', '2026-01-30', NULL, NULL, '2026-02-02 20:38:30'),
(5, 'maize', 'Luuka Central Market', 3550.00, 'kg', 'Market Survey', '2026-01-26', NULL, NULL, '2026-02-02 20:38:30'),
(6, 'maize', 'Irongo Market', 3300.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(7, 'maize', 'Irongo Market', 3250.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(8, 'maize', 'Irongo Market', 3350.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(9, 'maize', 'Nawampiti Market', 3700.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(10, 'maize', 'Nawampiti Market', 3650.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(11, 'maize', 'Bukooma Market', 3400.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(12, 'maize', 'Bukooma Market', 3380.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(13, 'sugar_cane', 'Luuka Central Market', 250000.00, 'ton', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(14, 'sugar_cane', 'Luuka Central Market', 245000.00, 'ton', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(15, 'sugar_cane', 'Luuka Central Market', 248000.00, 'ton', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(16, 'sugar_cane', 'Luuka Central Market', 252000.00, 'ton', 'Market Survey', '2026-01-26', NULL, NULL, '2026-02-02 20:38:30'),
(17, 'sugar_cane', 'Irongo Market', 240000.00, 'ton', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(18, 'sugar_cane', 'Irongo Market', 238000.00, 'ton', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(19, 'sugar_cane', 'Nawampiti Market', 255000.00, 'ton', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(20, 'sugar_cane', 'Nawampiti Market', 253000.00, 'ton', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(21, 'vegetables', 'Luuka Central Market', 2000.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(22, 'vegetables', 'Luuka Central Market', 1950.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(23, 'vegetables', 'Luuka Central Market', 2100.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(24, 'vegetables', 'Irongo Market', 1800.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(25, 'vegetables', 'Irongo Market', 1850.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(26, 'vegetables', 'Nawampiti Market', 2200.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(27, 'vegetables', 'Nawampiti Market', 2150.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(28, 'poultry', 'Luuka Central Market', 18000.00, 'bird', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(29, 'poultry', 'Luuka Central Market', 17500.00, 'bird', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(30, 'poultry', 'Luuka Central Market', 18500.00, 'bird', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(31, 'poultry', 'Irongo Market', 17000.00, 'bird', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(32, 'poultry', 'Irongo Market', 16800.00, 'bird', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(33, 'poultry', 'Nawampiti Market', 19000.00, 'bird', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(34, 'poultry', 'Nawampiti Market', 18800.00, 'bird', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(35, 'beans', 'Luuka Central Market', 4500.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(36, 'beans', 'Luuka Central Market', 4400.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(37, 'beans', 'Luuka Central Market', 4600.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(38, 'beans', 'Irongo Market', 4200.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(39, 'beans', 'Irongo Market', 4150.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(40, 'beans', 'Nawampiti Market', 4700.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(41, 'beans', 'Nawampiti Market', 4650.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(42, 'coffee', 'Luuka Central Market', 8500.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(43, 'coffee', 'Luuka Central Market', 8400.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(44, 'coffee', 'Luuka Central Market', 8600.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(45, 'coffee', 'Irongo Market', 8200.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(46, 'coffee', 'Irongo Market', 8100.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(47, 'coffee', 'Nawampiti Market', 8800.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(48, 'coffee', 'Nawampiti Market', 8750.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(49, 'cassava', 'Luuka Central Market', 1500.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(50, 'cassava', 'Luuka Central Market', 1450.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(51, 'cassava', 'Luuka Central Market', 1550.00, 'kg', 'Market Survey', '2026-01-31', NULL, NULL, '2026-02-02 20:38:30'),
(52, 'cassava', 'Irongo Market', 1400.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(53, 'cassava', 'Irongo Market', 1380.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(54, 'cassava', 'Nawampiti Market', 1600.00, 'kg', 'Market Survey', '2026-02-02', NULL, NULL, '2026-02-02 20:38:30'),
(55, 'cassava', 'Nawampiti Market', 1580.00, 'kg', 'Market Survey', '2026-02-01', NULL, NULL, '2026-02-02 20:38:30'),
(56, 'maize', 'Luuka Central Market', 3500.00, 'kg', 'Market Survey', '2026-01-23', NULL, NULL, '2026-02-02 20:38:30'),
(57, 'maize', 'Luuka Central Market', 3480.00, 'kg', 'Market Survey', '2026-01-19', NULL, NULL, '2026-02-02 20:38:30'),
(58, 'maize', 'Luuka Central Market', 3520.00, 'kg', 'Market Survey', '2026-01-12', NULL, NULL, '2026-02-02 20:38:30'),
(59, 'maize', 'Luuka Central Market', 3550.00, 'kg', 'Market Survey', '2026-01-05', NULL, NULL, '2026-02-02 20:38:30'),
(60, 'sugar_cane', 'Luuka Central Market', 250000.00, 'ton', 'Market Survey', '2026-01-23', NULL, NULL, '2026-02-02 20:38:30'),
(61, 'sugar_cane', 'Luuka Central Market', 248000.00, 'ton', 'Market Survey', '2026-01-19', NULL, NULL, '2026-02-02 20:38:30'),
(62, 'sugar_cane', 'Luuka Central Market', 252000.00, 'ton', 'Market Survey', '2026-01-12', NULL, NULL, '2026-02-02 20:38:30'),
(63, 'sugar_cane', 'Luuka Central Market', 255000.00, 'ton', 'Market Survey', '2026-01-05', NULL, NULL, '2026-02-02 20:38:30'),
(64, 'vegetables', 'Luuka Central Market', 2000.00, 'kg', 'Market Survey', '2026-01-23', NULL, NULL, '2026-02-02 20:38:30'),
(65, 'vegetables', 'Luuka Central Market', 1980.00, 'kg', 'Market Survey', '2026-01-19', NULL, NULL, '2026-02-02 20:38:30'),
(66, 'vegetables', 'Luuka Central Market', 2050.00, 'kg', 'Market Survey', '2026-01-12', NULL, NULL, '2026-02-02 20:38:30'),
(67, 'vegetables', 'Luuka Central Market', 2100.00, 'kg', 'Market Survey', '2026-01-05', NULL, NULL, '2026-02-02 20:38:30');

-- --------------------------------------------------------

--
-- Table structure for table `price_predictions`
--

CREATE TABLE `price_predictions` (
  `id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `prediction_date` date NOT NULL,
  `predicted_min_price` decimal(10,2) NOT NULL,
  `predicted_avg_price` decimal(10,2) NOT NULL,
  `predicted_max_price` decimal(10,2) NOT NULL,
  `confidence_score` decimal(3,2) DEFAULT 0.00,
  `model_version` varchar(20) DEFAULT 'v1.0',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `price_reports`
--

CREATE TABLE `price_reports` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `market_location` varchar(100) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `unit` varchar(20) NOT NULL,
  `quantity_available` decimal(10,2) DEFAULT NULL,
  `quality_rating` enum('poor','fair','good','excellent') DEFAULT NULL,
  `photo_url` varchar(255) DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `verification_status` enum('pending','verified','rejected') DEFAULT 'pending',
  `verified_by` int(11) DEFAULT NULL,
  `verified_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `price_sources`
--

CREATE TABLE `price_sources` (
  `id` int(11) NOT NULL,
  `source_name` varchar(100) NOT NULL,
  `source_type` enum('manual','api','scraper','user_reported','government') DEFAULT 'manual',
  `reliability_score` decimal(3,2) DEFAULT 1.00 COMMENT 'Score from 0.00 to 1.00',
  `last_update` timestamp NULL DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `price_sources`
--

INSERT INTO `price_sources` (`id`, `source_name`, `source_type`, `reliability_score`, `last_update`, `is_active`, `created_at`) VALUES
(1, 'AIMS User Reports', 'user_reported', 0.85, NULL, 1, '2026-02-02 20:18:34'),
(2, 'Market Surveys', 'manual', 0.95, NULL, 1, '2026-02-02 20:18:34'),
(3, 'MAAIF Official Data', 'government', 1.00, NULL, 1, '2026-02-02 20:18:34'),
(4, 'Extension Officers', 'manual', 0.90, NULL, 1, '2026-02-02 20:18:34');

-- --------------------------------------------------------

--
-- Table structure for table `price_watchlist`
--

CREATE TABLE `price_watchlist` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `preferred_locations` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`preferred_locations`)),
  `notify_on_change` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `seller_id` int(11) NOT NULL,
  `enterprise_id` int(11) DEFAULT NULL,
  `product_name` varchar(100) NOT NULL,
  `category` enum('sugar_cane','poultry','maize','vegetables','coffee','beans','cassava','bananas','dairy','livestock','other') NOT NULL,
  `description` text DEFAULT NULL,
  `quantity` decimal(10,2) NOT NULL,
  `unit` varchar(20) NOT NULL,
  `price_per_unit` decimal(10,2) NOT NULL,
  `location` varchar(100) DEFAULT NULL,
  `images` text DEFAULT NULL,
  `status` enum('available','sold','reserved','expired') DEFAULT 'available',
  `views` int(11) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `expires_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `seller_id`, `enterprise_id`, `product_name`, `category`, `description`, `quantity`, `unit`, `price_per_unit`, `location`, `images`, `status`, `views`, `created_at`, `updated_at`, `expires_at`) VALUES
(1, 3, NULL, 'Fresh Beans for Sale', 'beans', 'Freshly harvested beans for sale', 50.00, 'sack', 45000.00, 'Luuka,Luuka Town council,Busonga Ward,Bukaboli', '[\"assets/uploads/products/697b3094a3bff_1769681044.jpeg\"]', 'available', 11, '2026-01-29 10:04:04', '2026-02-07 06:35:28', NULL);

-- --------------------------------------------------------

--
-- Table structure for table `product_inquiries`
--

CREATE TABLE `product_inquiries` (
  `id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `message` text NOT NULL,
  `status` enum('pending','responded','closed') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `product_inquiries`
--
DELIMITER $$
CREATE TRIGGER `notify_product_inquiry` AFTER INSERT ON `product_inquiries` FOR EACH ROW BEGIN
    INSERT INTO notifications (user_id, title, message, type, icon, link)
    SELECT 
        p.seller_id,
        'New Product Inquiry',
        CONCAT((SELECT full_name FROM users WHERE id = NEW.buyer_id), ' asked about your product'),
        'info',
        'message-circle',
        CONCAT('/products/view.php?id=', NEW.product_id)
    FROM products p
    WHERE p.id = NEW.product_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `profile_photos`
--

CREATE TABLE `profile_photos` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `photo_url` varchar(255) NOT NULL,
  `photo_type` enum('profile','cover','gallery') DEFAULT 'gallery',
  `caption` text DEFAULT NULL,
  `is_current` tinyint(1) DEFAULT 0 COMMENT 'For profile/cover photos',
  `likes_count` int(11) DEFAULT 0,
  `comments_count` int(11) DEFAULT 0,
  `upload_date` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `profile_photos`
--

INSERT INTO `profile_photos` (`id`, `user_id`, `photo_url`, `photo_type`, `caption`, `is_current`, `likes_count`, `comments_count`, `upload_date`) VALUES
(1, 9, 'assets/uploads/profiles/profile_697f34323347d.jpeg', 'profile', NULL, 1, 0, 0, '2026-02-01 11:08:34'),
(2, 9, 'assets/uploads/profiles/cover_697f34423cfed.jpeg', 'cover', NULL, 1, 0, 0, '2026-02-01 11:08:50');

-- --------------------------------------------------------

--
-- Table structure for table `profile_verifications`
--

CREATE TABLE `profile_verifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `verification_type` enum('phone','email','id_card','farm_ownership','business_license','professional') NOT NULL,
  `document_url` varchar(255) DEFAULT NULL,
  `status` enum('pending','approved','rejected') DEFAULT 'pending',
  `verified_by` int(11) DEFAULT NULL COMMENT 'Admin who verified',
  `verified_at` timestamp NULL DEFAULT NULL,
  `rejection_reason` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `profile_views`
--

CREATE TABLE `profile_views` (
  `id` int(11) NOT NULL,
  `profile_user_id` int(11) NOT NULL COMMENT 'Profile being viewed',
  `visitor_user_id` int(11) DEFAULT NULL COMMENT 'User viewing (NULL for anonymous)',
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `viewed_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `profile_views`
--

INSERT INTO `profile_views` (`id`, `profile_user_id`, `visitor_user_id`, `ip_address`, `user_agent`, `viewed_at`) VALUES
(1, 9, NULL, '0.0.0.0', 'Unknown', '2026-02-01 18:32:12');

--
-- Triggers `profile_views`
--
DELIMITER $$
CREATE TRIGGER `increment_profile_view_count` AFTER INSERT ON `profile_views` FOR EACH ROW BEGIN
    UPDATE user_profiles 
    SET profile_views = profile_views + 1 
    WHERE user_id = NEW.profile_user_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `purchase_requests`
--

CREATE TABLE `purchase_requests` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `product_type` varchar(100) NOT NULL,
  `quantity` decimal(10,2) NOT NULL,
  `unit` varchar(20) DEFAULT 'kg',
  `specifications` text DEFAULT NULL,
  `quality_requirements` text DEFAULT NULL,
  `required_delivery_date` date DEFAULT NULL,
  `delivery_location` varchar(200) DEFAULT NULL,
  `budget_range` varchar(50) DEFAULT NULL,
  `status` enum('pending','quoted','accepted','rejected','completed') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `push_queue`
--

CREATE TABLE `push_queue` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `notification_id` int(11) DEFAULT NULL,
  `message_id` int(11) DEFAULT NULL,
  `title` varchar(255) NOT NULL,
  `body` text NOT NULL,
  `data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`data`)),
  `status` enum('pending','sent','failed') DEFAULT 'pending',
  `attempts` int(11) DEFAULT 0,
  `error_message` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `sent_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `push_queue`
--

INSERT INTO `push_queue` (`id`, `user_id`, `notification_id`, `message_id`, `title`, `body`, `data`, `status`, `attempts`, `error_message`, `created_at`, `sent_at`) VALUES
(1, 2, 9, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-06 06:51:10', NULL),
(2, 2, 10, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-06 17:16:54', NULL),
(3, 9, 11, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-06 17:45:48', NULL),
(4, 3, 12, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-06 17:47:28', NULL),
(5, 9, 13, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-06 17:48:20', NULL),
(6, 9, 14, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-07 06:23:09', NULL),
(7, 9, 15, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-07 06:25:03', NULL),
(8, 3, 16, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-07 06:44:14', NULL),
(9, 3, 17, NULL, '', '', NULL, 'pending', 0, NULL, '2026-02-07 06:44:14', NULL);

-- --------------------------------------------------------

--
-- Table structure for table `push_subscriptions`
--

CREATE TABLE `push_subscriptions` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `endpoint` text NOT NULL,
  `p256dh` varchar(255) NOT NULL,
  `auth` varchar(255) NOT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `quality_specifications`
--

CREATE TABLE `quality_specifications` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `product_type` varchar(100) NOT NULL,
  `specification_name` varchar(200) NOT NULL,
  `moisture_content` varchar(50) DEFAULT NULL,
  `purity_level` varchar(50) DEFAULT NULL,
  `color_grade` varchar(50) DEFAULT NULL,
  `size_requirements` varchar(100) DEFAULT NULL,
  `packaging_requirements` text DEFAULT NULL,
  `additional_requirements` text DEFAULT NULL,
  `is_default` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `quote_responses`
--

CREATE TABLE `quote_responses` (
  `id` int(11) NOT NULL,
  `request_id` int(11) NOT NULL,
  `seller_id` int(11) NOT NULL,
  `quoted_price` decimal(10,2) NOT NULL,
  `quantity_available` decimal(10,2) NOT NULL,
  `delivery_date` date DEFAULT NULL,
  `delivery_cost` decimal(10,2) DEFAULT 0.00,
  `notes` text DEFAULT NULL,
  `status` enum('pending','accepted','rejected') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `quote_responses`
--
DELIMITER $$
CREATE TRIGGER `notify_buyer_quote_response` AFTER INSERT ON `quote_responses` FOR EACH ROW BEGIN
    INSERT INTO notifications (user_id, title, message, type, icon, link)
    SELECT 
        pr.buyer_id,
        'New Quote Received',
        CONCAT('You received a quote for your ', pr.product_type, ' request'),
        'success',
        'file-text',
        CONCAT('/buyer/purchase-requests.php?id=', pr.id)
    FROM purchase_requests pr
    WHERE pr.id = NEW.request_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `regions`
--

CREATE TABLE `regions` (
  `id` int(11) NOT NULL,
  `region_name` varchar(100) NOT NULL,
  `region_code` varchar(10) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `regions`
--

INSERT INTO `regions` (`id`, `region_name`, `region_code`, `created_at`) VALUES
(1, 'Busoga', 'BUS', '2026-01-26 21:19:04'),
(2, 'Central', 'CEN', '2026-01-26 21:19:04'),
(3, 'Western', 'WST', '2026-01-26 21:19:04'),
(4, 'Eastern', 'EST', '2026-01-26 21:19:04'),
(5, 'Northern', 'NTH', '2026-01-26 21:19:04');

-- --------------------------------------------------------

--
-- Table structure for table `reports`
--

CREATE TABLE `reports` (
  `id` int(11) NOT NULL,
  `reporter_id` int(11) NOT NULL,
  `report_type` enum('product','user','message','other') NOT NULL,
  `reported_item_id` int(11) NOT NULL,
  `reason` text NOT NULL,
  `status` enum('pending','reviewing','resolved','dismissed') DEFAULT 'pending',
  `admin_notes` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `resolved_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `reviews`
--

CREATE TABLE `reviews` (
  `id` int(11) NOT NULL,
  `reviewer_id` int(11) NOT NULL,
  `reviewed_user_id` int(11) NOT NULL,
  `order_id` int(11) DEFAULT NULL,
  `rating` int(11) NOT NULL CHECK (`rating` between 1 and 5),
  `review_text` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `role_permissions`
--

CREATE TABLE `role_permissions` (
  `id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  `permission_id` int(11) NOT NULL,
  `granted_at` timestamp NULL DEFAULT current_timestamp(),
  `granted_by` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `role_permissions`
--

INSERT INTO `role_permissions` (`id`, `role_id`, `permission_id`, `granted_at`, `granted_by`) VALUES
(1, 1, 4, '2026-02-07 08:13:03', NULL),
(2, 1, 5, '2026-02-07 08:13:03', NULL),
(3, 1, 6, '2026-02-07 08:13:03', NULL),
(4, 1, 7, '2026-02-07 08:13:03', NULL),
(5, 1, 8, '2026-02-07 08:13:03', NULL),
(6, 1, 19, '2026-02-07 08:13:03', NULL),
(7, 1, 20, '2026-02-07 08:13:03', NULL),
(8, 1, 11, '2026-02-07 08:13:03', NULL),
(9, 1, 12, '2026-02-07 08:13:03', NULL),
(10, 1, 15, '2026-02-07 08:13:03', NULL),
(11, 1, 16, '2026-02-07 08:13:03', NULL),
(12, 1, 17, '2026-02-07 08:13:03', NULL),
(13, 1, 18, '2026-02-07 08:13:03', NULL),
(14, 1, 1, '2026-02-07 08:13:03', NULL),
(15, 1, 3, '2026-02-07 08:13:03', NULL),
(16, 1, 21, '2026-02-07 08:13:03', NULL),
(17, 1, 22, '2026-02-07 08:13:03', NULL),
(18, 1, 23, '2026-02-07 08:13:03', NULL),
(19, 1, 9, '2026-02-07 08:13:03', NULL),
(20, 1, 10, '2026-02-07 08:13:03', NULL),
(21, 1, 13, '2026-02-07 08:13:03', NULL),
(22, 1, 14, '2026-02-07 08:13:03', NULL),
(23, 1, 2, '2026-02-07 08:13:03', NULL),
(32, 2, 5, '2026-02-07 08:13:03', NULL),
(33, 2, 7, '2026-02-07 08:13:03', NULL),
(34, 2, 12, '2026-02-07 08:13:03', NULL),
(35, 2, 6, '2026-01-26 21:54:57', NULL),
(36, 2, 8, '2026-02-07 08:13:03', NULL),
(37, 2, 10, '2026-02-07 08:13:03', NULL),
(38, 2, 16, '2026-02-07 08:13:03', NULL),
(39, 2, 17, '2026-02-07 08:13:03', NULL),
(40, 2, 9, '2026-02-07 08:13:03', NULL),
(41, 2, 14, '2026-02-07 08:13:03', NULL),
(42, 2, 15, '2026-02-07 08:13:03', NULL),
(43, 2, 11, '2026-02-07 08:13:03', NULL),
(44, 2, 19, '2026-02-07 08:13:03', NULL),
(45, 2, 21, '2026-02-07 08:13:03', NULL),
(46, 2, 4, '2026-02-07 08:13:03', NULL),
(47, 2, 18, '2026-02-07 08:13:03', NULL),
(48, 2, 2, '2026-02-07 08:13:03', NULL),
(49, 2, 1, '2026-02-07 08:13:03', NULL),
(50, 2, 3, '2026-02-07 08:13:03', NULL),
(51, 2, 13, '2026-02-07 08:13:03', NULL),
(52, 2, 20, '2026-02-07 08:13:03', NULL),
(63, 3, 16, '2026-01-26 21:54:57', NULL),
(64, 3, 17, '2026-01-26 21:54:57', NULL),
(65, 3, 15, '2026-01-26 21:54:57', NULL),
(66, 3, 11, '2026-01-26 21:54:57', NULL),
(67, 3, 18, '2026-01-26 21:54:57', NULL),
(68, 3, 2, '2026-01-26 21:54:57', NULL),
(69, 3, 1, '2026-01-26 21:54:57', NULL),
(70, 4, 5, '2026-01-26 21:54:57', NULL),
(71, 4, 7, '2026-01-26 21:54:57', NULL),
(72, 4, 19, '2026-01-26 21:54:57', NULL),
(73, 4, 4, '2026-01-26 21:54:57', NULL),
(74, 4, 1, '2026-01-26 21:54:57', NULL),
(75, 4, 3, '2026-01-26 21:54:57', NULL),
(76, 4, 20, '2026-01-26 21:54:57', NULL),
(77, 5, 2, '2026-01-26 21:54:57', NULL),
(78, 5, 1, '2026-01-26 21:54:57', NULL),
(79, 5, 3, '2026-01-26 21:54:57', NULL),
(80, 5, 13, '2026-01-26 21:54:57', NULL),
(81, 5, 20, '2026-01-26 21:54:57', NULL),
(82, 1, 31, '2026-02-07 08:13:03', 5),
(83, 1, 32, '2026-02-07 08:13:03', 5),
(84, 1, 24, '2026-02-07 08:13:03', 5),
(85, 1, 25, '2026-02-07 08:13:03', 5),
(86, 1, 26, '2026-02-07 08:13:03', 5),
(87, 1, 27, '2026-02-07 08:13:03', 5),
(88, 1, 28, '2026-02-07 08:13:03', 5),
(89, 1, 29, '2026-02-07 08:13:03', 5),
(90, 1, 30, '2026-02-07 08:13:03', 5),
(91, 1, 33, '2026-02-07 08:13:03', 5),
(92, 1, 34, '2026-02-07 08:13:03', 5),
(97, 2, 27, '2026-02-07 08:13:03', 5),
(98, 2, 33, '2026-02-07 08:13:03', 5),
(99, 2, 34, '2026-02-07 08:13:03', 5),
(100, 2, 29, '2026-02-07 08:13:03', 5),
(101, 2, 31, '2026-02-07 08:13:03', 5),
(102, 2, 30, '2026-02-07 08:13:03', 5),
(103, 2, 32, '2026-02-07 08:13:03', 5),
(104, 2, 26, '2026-02-07 08:13:03', 5),
(105, 2, 28, '2026-02-07 08:13:03', 5),
(106, 2, 24, '2026-02-07 08:13:03', 5),
(113, 2, 25, '2026-02-07 08:13:03', 5);

--
-- Triggers `role_permissions`
--
DELIMITER $$
CREATE TRIGGER `log_permission_changes` AFTER INSERT ON `role_permissions` FOR EACH ROW BEGIN
    DECLARE role_name_val VARCHAR(50);
    DECLARE perm_name_val VARCHAR(100);

    IF @disable_permission_log IS NULL THEN
        SELECT role_name INTO role_name_val
        FROM admin_roles WHERE id = NEW.role_id;

        SELECT permission_name INTO perm_name_val
        FROM admin_permissions WHERE id = NEW.permission_id;

        INSERT INTO admin_activity_log
            (admin_id, action_type, action_description, affected_table, affected_record_id)
        VALUES
            (COALESCE(NEW.granted_by, @current_admin_id, 1),
             'grant_permission',
             CONCAT('Granted "', perm_name_val, '" to "', role_name_val, '"'),
             'role_permissions',
             NEW.id);
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `scheduled_tasks`
--

CREATE TABLE `scheduled_tasks` (
  `id` int(11) NOT NULL,
  `task_name` varchar(100) NOT NULL,
  `task_type` enum('backup','cleanup','report','notification','maintenance','security_scan','update_check') NOT NULL,
  `schedule_pattern` varchar(50) NOT NULL COMMENT 'Cron pattern',
  `is_active` tinyint(1) DEFAULT 1,
  `last_run` timestamp NULL DEFAULT NULL,
  `next_run` timestamp NULL DEFAULT NULL,
  `last_status` enum('success','failed','skipped') DEFAULT NULL,
  `last_duration` int(11) DEFAULT NULL COMMENT 'Seconds',
  `run_count` int(11) DEFAULT 0,
  `failure_count` int(11) DEFAULT 0,
  `max_failures` int(11) DEFAULT 5,
  `error_message` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `seasonal_calendar`
--

CREATE TABLE `seasonal_calendar` (
  `id` int(11) NOT NULL,
  `region` varchar(100) DEFAULT 'Luuka',
  `season_name` varchar(100) NOT NULL,
  `season_type` enum('first_season','second_season','dry_season') NOT NULL,
  `start_month` int(11) NOT NULL,
  `end_month` int(11) NOT NULL,
  `description` text DEFAULT NULL,
  `recommended_crops` text DEFAULT NULL,
  `activities` text DEFAULT NULL,
  `weather_pattern` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `seasonal_calendar`
--

INSERT INTO `seasonal_calendar` (`id`, `region`, `season_name`, `season_type`, `start_month`, `end_month`, `description`, `recommended_crops`, `activities`, `weather_pattern`, `created_at`) VALUES
(1, 'Luuka', 'First Rainy Season', 'first_season', 3, 5, 'Main planting season with reliable rainfall', 'Maize, Beans, Groundnuts, Cassava, Vegetables', 'Land preparation, Planting, First weeding', 'Heavy rainfall, moderate temperatures', '2026-02-02 14:52:15'),
(2, 'Luuka', 'Second Rainy Season', 'second_season', 9, 11, 'Second planting season with moderate rainfall', 'Vegetables, Beans, Maize (short season), Sweet potatoes', 'Planting, Maintenance, Harvesting first season crops', 'Moderate rainfall, warm temperatures', '2026-02-02 14:52:15'),
(3, 'Luuka', 'Dry Season', 'dry_season', 12, 2, 'Hot and dry period, irrigation needed', 'Irrigated vegetables, Bananas (with irrigation), Passion fruits', 'Irrigation, Post-harvest activities, Land preparation', 'Low rainfall, high temperatures', '2026-02-02 14:52:15');

-- --------------------------------------------------------

--
-- Table structure for table `seasonal_price_patterns`
--

CREATE TABLE `seasonal_price_patterns` (
  `id` int(11) NOT NULL,
  `product_type` varchar(50) NOT NULL,
  `month` tinyint(2) NOT NULL COMMENT 'Month 1-12',
  `avg_price_index` decimal(5,2) NOT NULL COMMENT 'Relative to annual average (1.00 = average)',
  `typical_low_price` decimal(10,2) DEFAULT NULL,
  `typical_high_price` decimal(10,2) DEFAULT NULL,
  `volatility_score` decimal(3,2) DEFAULT NULL,
  `data_points` int(11) DEFAULT 0,
  `last_calculated` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `security_threats`
--

CREATE TABLE `security_threats` (
  `id` int(11) NOT NULL,
  `threat_type` enum('brute_force','sql_injection','xss','ddos','unauthorized_access','suspicious_activity','malware') NOT NULL,
  `severity` enum('low','medium','high','critical') DEFAULT 'medium',
  `ip_address` varchar(45) NOT NULL,
  `user_agent` text DEFAULT NULL,
  `request_uri` text DEFAULT NULL,
  `request_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`request_data`)),
  `user_id` int(11) DEFAULT NULL,
  `action_taken` enum('logged','blocked','banned','notified') DEFAULT 'logged',
  `is_resolved` tinyint(1) DEFAULT 0,
  `resolved_by` int(11) DEFAULT NULL,
  `resolved_at` timestamp NULL DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `detected_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `server_metrics`
--

CREATE TABLE `server_metrics` (
  `id` int(11) NOT NULL,
  `metric_type` enum('cpu','memory','disk','network','response_time','database') NOT NULL,
  `metric_value` decimal(10,2) NOT NULL,
  `metric_unit` varchar(20) DEFAULT NULL COMMENT '%, MB, ms, etc',
  `threshold_warning` decimal(10,2) DEFAULT NULL,
  `threshold_critical` decimal(10,2) DEFAULT NULL,
  `is_critical` tinyint(1) DEFAULT 0,
  `server_name` varchar(100) DEFAULT 'main',
  `recorded_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `server_metrics`
--
DELIMITER $$
CREATE TRIGGER `alert_critical_server_metric` AFTER INSERT ON `server_metrics` FOR EACH ROW BEGIN
    IF NEW.is_critical = 1 THEN
        INSERT INTO system_alerts (
            alert_type, severity, title, message, alert_data
        ) VALUES (
            CASE NEW.metric_type
                WHEN 'cpu' THEN 'high_cpu'
                WHEN 'memory' THEN 'low_memory'
                WHEN 'disk' THEN 'disk_full'
                ELSE 'server_down'
            END,
            'critical',
            CONCAT('Critical: High ', UPPER(NEW.metric_type)),
            CONCAT(UPPER(NEW.metric_type), ' usage at ', NEW.metric_value, NEW.metric_unit),
            JSON_OBJECT('metric_id', NEW.id, 'value', NEW.metric_value, 'server', NEW.server_name)
        );
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `service_participants`
--

CREATE TABLE `service_participants` (
  `id` int(11) NOT NULL,
  `service_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `attendance_status` enum('registered','attended','absent') DEFAULT 'registered',
  `feedback` text DEFAULT NULL,
  `rating` int(11) DEFAULT NULL CHECK (`rating` between 1 and 5),
  `registered_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `session_keys`
--

CREATE TABLE `session_keys` (
  `id` int(11) NOT NULL,
  `chat_id` int(11) NOT NULL,
  `session_key` varchar(255) NOT NULL,
  `expires_at` timestamp NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `skill_endorsements`
--

CREATE TABLE `skill_endorsements` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `skill_name` varchar(100) NOT NULL,
  `endorser_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `ssl_certificates`
--

CREATE TABLE `ssl_certificates` (
  `id` int(11) NOT NULL,
  `domain_name` varchar(255) NOT NULL,
  `certificate_issuer` varchar(200) DEFAULT NULL,
  `issued_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `days_until_expiry` int(11) DEFAULT NULL,
  `is_valid` tinyint(1) DEFAULT 1,
  `is_expiring_soon` tinyint(1) DEFAULT 0 COMMENT 'Less than 30 days',
  `auto_renew` tinyint(1) DEFAULT 0,
  `last_checked` timestamp NULL DEFAULT NULL,
  `error_message` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `story_views`
--

CREATE TABLE `story_views` (
  `id` int(11) NOT NULL,
  `story_id` int(11) NOT NULL,
  `viewer_id` int(11) NOT NULL,
  `viewed_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `story_views`
--

INSERT INTO `story_views` (`id`, `story_id`, `viewer_id`, `viewed_at`) VALUES
(1, 2, 3, '2026-02-06 19:13:01'),
(2, 1, 3, '2026-02-06 19:13:06');

--
-- Triggers `story_views`
--
DELIMITER $$
CREATE TRIGGER `update_story_views_count` AFTER INSERT ON `story_views` FOR EACH ROW BEGIN
    UPDATE user_stories SET views_count = views_count + 1 WHERE id = NEW.story_id;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `subcounties`
--

CREATE TABLE `subcounties` (
  `id` int(11) NOT NULL,
  `district_id` int(11) NOT NULL,
  `subcounty_name` varchar(100) NOT NULL,
  `subcounty_code` varchar(10) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `subcounties`
--

INSERT INTO `subcounties` (`id`, `district_id`, `subcounty_name`, `subcounty_code`, `created_at`) VALUES
(2, 1, 'Bukanga', 'BKG', '2026-01-26 21:19:04'),
(3, 1, 'Ikumbya', 'IKM', '2026-01-26 21:19:04'),
(5, 1, 'Luuka Town Council', 'LTC', '2026-01-26 21:19:04'),
(6, 1, 'Nawampiti', 'NWP', '2026-01-26 21:19:04'),
(7, 1, 'Irongo', 'IRG', '2026-01-26 21:19:04'),
(9, 2, 'NABITENDE', 'NBT', '2026-01-27 20:52:20'),
(10, 2, 'NAMBALE', 'NMB', '2026-01-27 20:52:20'),
(11, 2, 'NAMUNGALWE TOWN COUNCIL', 'NMT', '2026-01-27 20:52:20'),
(12, 2, 'NAWANDALA', 'NWD', '2026-01-27 20:52:20'),
(13, 2, 'KIDAAGO', 'KDG', '2026-01-27 20:52:20'),
(14, 2, 'BULAMAGI', 'BLG', '2026-01-27 20:52:20'),
(15, 2, 'NAKALAMA', 'NKL', '2026-01-27 20:52:20'),
(16, 2, 'NAKIGO', 'NKG', '2026-01-27 20:52:20'),
(17, 2, 'NAWANYINGI', 'NWY', '2026-01-27 20:52:20'),
(18, 2, 'CENTRAL DIVISION', 'CTD', '2026-01-27 20:52:20'),
(19, 2, 'NORTHERN DIVISION', 'NTD', '2026-01-27 20:52:20'),
(20, 3, 'BUSEDDE', 'BSD', '2026-01-27 20:52:20'),
(21, 3, 'KAKIRA TOWN COUNCIL', 'KKR', '2026-01-27 20:52:20'),
(22, 3, 'BUTAGAYA', 'BTG', '2026-01-27 20:52:20'),
(23, 3, 'NAMAGERA TOWN COUNCIL', 'NMG', '2026-01-27 20:52:20'),
(24, 3, 'BUWENGE', 'BWG', '2026-01-27 20:52:20'),
(25, 3, 'BUYENGO TOWN COUNCIL', 'BYG', '2026-01-27 20:52:20'),
(26, 3, 'BUWENGE TOWN COUNCIL', 'BWT', '2026-01-27 20:52:20'),
(27, 1, 'Bulongo', 'BLO', '2026-01-27 21:00:00'),
(28, 1, 'Bukoma', 'BKM', '2026-01-27 21:00:00'),
(29, 1, 'Bukoova Town Council', 'BKV', '2026-01-27 21:00:00'),
(30, 1, 'Busalamu Town Council', 'BSL', '2026-01-27 21:00:00'),
(31, 1, 'Waibuga', 'WBG', '2026-01-27 21:00:00'),
(32, 1, 'Bulanga Town Council', 'BLN', '2026-01-27 21:00:00'),
(33, 1, 'Kyanvuma Town Council', 'KYV', '2026-01-27 21:00:00');

-- --------------------------------------------------------

--
-- Table structure for table `supplier_ratings`
--

CREATE TABLE `supplier_ratings` (
  `id` int(11) NOT NULL,
  `buyer_id` int(11) NOT NULL,
  `supplier_id` int(11) NOT NULL,
  `order_id` int(11) DEFAULT NULL,
  `quality_rating` int(11) DEFAULT NULL CHECK (`quality_rating` between 1 and 5),
  `delivery_rating` int(11) DEFAULT NULL CHECK (`delivery_rating` between 1 and 5),
  `communication_rating` int(11) DEFAULT NULL CHECK (`communication_rating` between 1 and 5),
  `overall_rating` decimal(3,2) DEFAULT NULL,
  `review_text` text DEFAULT NULL,
  `would_recommend` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `supplier_ratings`
--
DELIMITER $$
CREATE TRIGGER `calculate_supplier_overall_rating` BEFORE INSERT ON `supplier_ratings` FOR EACH ROW BEGIN
    SET NEW.overall_rating = (
        NEW.quality_rating + 
        NEW.delivery_rating + 
        NEW.communication_rating
    ) / 3;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `system_alerts`
--

CREATE TABLE `system_alerts` (
  `id` int(11) NOT NULL,
  `alert_type` enum('server_down','high_cpu','low_memory','disk_full','security_breach','backup_failed','unusual_traffic','ssl_expiring','database_slow') NOT NULL,
  `severity` enum('info','warning','critical') DEFAULT 'warning',
  `title` varchar(200) NOT NULL,
  `message` text NOT NULL,
  `alert_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`alert_data`)),
  `is_acknowledged` tinyint(1) DEFAULT 0,
  `acknowledged_by` int(11) DEFAULT NULL,
  `acknowledged_at` timestamp NULL DEFAULT NULL,
  `is_resolved` tinyint(1) DEFAULT 0,
  `resolved_by` int(11) DEFAULT NULL,
  `resolved_at` timestamp NULL DEFAULT NULL,
  `notified_admins` text DEFAULT NULL COMMENT 'Comma-separated admin IDs',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `system_audit_log`
--

CREATE TABLE `system_audit_log` (
  `id` int(11) NOT NULL,
  `event_type` enum('login','logout','create','update','delete','approve','reject','export','import') NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `entity_type` varchar(50) DEFAULT NULL COMMENT 'Table or entity affected',
  `entity_id` int(11) DEFAULT NULL,
  `old_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Previous state before change' CHECK (json_valid(`old_data`)),
  `new_data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'New state after change' CHECK (json_valid(`new_data`)),
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `system_audit_log`
--

INSERT INTO `system_audit_log` (`id`, `event_type`, `user_id`, `entity_type`, `entity_id`, `old_data`, `new_data`, `ip_address`, `user_agent`, `created_at`) VALUES
(1, 'delete', NULL, 'users', 1, '{\"full_name\": \"Musumba Jonathan\", \"phone_number\": \"+256787842061\", \"user_type\": \"admin\", \"created_at\": \"2026-01-25 15:45:24\"}', NULL, NULL, NULL, '2026-01-26 22:27:52');

-- --------------------------------------------------------

--
-- Table structure for table `system_settings`
--

CREATE TABLE `system_settings` (
  `id` int(11) NOT NULL,
  `setting_key` varchar(100) NOT NULL,
  `setting_value` text DEFAULT NULL,
  `setting_type` enum('string','number','boolean','json') DEFAULT 'string',
  `description` text DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `system_settings`
--

INSERT INTO `system_settings` (`id`, `setting_key`, `setting_value`, `setting_type`, `description`, `updated_at`) VALUES
(1, 'site_name', 'AIMS - Agricultural Information & Market Linkage', 'string', 'Application name', '2026-01-25 12:45:24'),
(2, 'max_upload_size', '5242880', 'number', 'Maximum file upload size in bytes (5MB)', '2026-01-25 12:45:24'),
(3, 'enable_notifications', 'true', 'boolean', 'Enable push notifications', '2026-01-25 12:45:24'),
(4, 'ai_model', 'claude-sonnet-4-5', 'string', 'AI model to use for assistance', '2026-01-25 12:45:24'),
(5, 'price_alert_frequency', '86400', 'number', 'Price alert check frequency in seconds (24 hours)', '2026-01-25 12:45:24'),
(6, 'farmer_interests', '[\"Crop Farming\",\"Livestock\",\"Poultry\",\"Dairy\",\"Fisheries\",\"Beekeeping\",\"Agroforestry\",\"Organic Farming\",\"Irrigation\",\"Post-harvest Management\",\"Agricultural Marketing\",\"Farm Equipment\",\"Soil Management\",\"Pest Control\",\"Climate Smart Agriculture\"]', 'json', 'Available farming interests', '2026-02-01 09:52:15'),
(7, 'farmer_skills', '[\"Maize Farming\",\"Rice Cultivation\",\"Coffee Growing\",\"Banana Farming\",\"Vegetable Production\",\"Cattle Rearing\",\"Pig Farming\",\"Chicken Rearing\",\"Fish Farming\",\"Beekeeping\",\"Soil Testing\",\"Composting\",\"Drip Irrigation\",\"Greenhouse Farming\",\"Value Addition\"]', 'json', 'Available farming skills', '2026-02-01 09:52:15'),
(8, 'farming_languages', '[\"English\",\"Lusoga\",\"Luganda\",\"Swahili\",\"Runyankole\",\"Ateso\",\"Luo\",\"Lugbara\"]', 'json', 'Supported languages', '2026-02-01 09:52:15');

-- --------------------------------------------------------

--
-- Table structure for table `transactions`
--

CREATE TABLE `transactions` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `enterprise_id` int(11) DEFAULT NULL,
  `transaction_type` enum('income','expense') NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `amount` decimal(10,2) NOT NULL,
  `description` text DEFAULT NULL,
  `transaction_date` date NOT NULL,
  `receipt_url` varchar(255) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `transactions`
--

INSERT INTO `transactions` (`id`, `user_id`, `enterprise_id`, `transaction_type`, `category`, `amount`, `description`, `transaction_date`, `receipt_url`, `created_at`) VALUES
(1, 3, 1, 'expense', 'Rent', 6000000.00, 'Land Rent for 5 years', '2026-02-02', NULL, '2026-02-01 22:00:41'),
(2, 3, 1, 'expense', 'Other Expense', 720000.00, 'Clearing at 120000 per acre', '2025-08-03', NULL, '2026-02-01 22:02:45');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `phone_number` varchar(15) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `email` varchar(100) DEFAULT NULL,
  `region_id` int(11) DEFAULT NULL,
  `district_id` int(11) DEFAULT NULL,
  `subcounty_id` int(11) DEFAULT NULL,
  `parish_id` int(11) DEFAULT NULL,
  `village_id` int(11) DEFAULT NULL,
  `language_preference` enum('en','lusoga') DEFAULT 'en',
  `profile_picture` varchar(255) DEFAULT NULL,
  `user_type` enum('farmer','buyer','extension_officer','admin') DEFAULT 'farmer',
  `admin_role_id` int(11) DEFAULT NULL,
  `is_verified` tinyint(1) DEFAULT 0,
  `approval_status` enum('pending','approved','rejected') DEFAULT 'approved',
  `rejection_reason` text DEFAULT NULL,
  `is_active` tinyint(1) DEFAULT 1,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `last_login` timestamp NULL DEFAULT NULL,
  `last_activity` timestamp NULL DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `phone_number`, `password_hash`, `full_name`, `email`, `region_id`, `district_id`, `subcounty_id`, `parish_id`, `village_id`, `language_preference`, `profile_picture`, `user_type`, `admin_role_id`, `is_verified`, `approval_status`, `rejection_reason`, `is_active`, `created_at`, `updated_at`, `last_login`, `last_activity`, `ip_address`) VALUES
(2, '+256700000001', '$2y$12$pAgzKryt9RuIPgXpsr8SEuYJNVrKpKc/zmN.G5dXOZnt3HXXkRuYG', 'John Mwesigwa', NULL, NULL, NULL, NULL, NULL, NULL, 'en', NULL, 'extension_officer', NULL, 1, 'approved', NULL, 1, '2026-01-25 12:45:24', '2026-02-05 18:41:53', '2026-02-05 18:41:53', NULL, NULL),
(3, '+256777115678', '$2y$12$pAgzKryt9RuIPgXpsr8SEuYJNVrKpKc/zmN.G5dXOZnt3HXXkRuYG', 'Musumba Jonathan', NULL, NULL, NULL, NULL, NULL, NULL, 'en', NULL, 'farmer', NULL, 1, 'approved', NULL, 1, '2026-01-25 16:02:18', '2026-02-07 06:24:09', '2026-02-07 06:24:09', '2026-02-05 13:21:05', NULL),
(4, '+256758697337', '$2y$12$DL9YpfoJIR6cN18Zrw5.8ufT2qR9Nsf1kXOcO6GJk91LG3CfpBc/u', 'Mukisa Emmanuel', '', NULL, NULL, NULL, NULL, NULL, 'en', NULL, 'buyer', NULL, 1, 'approved', NULL, 1, '2026-01-26 21:47:56', '2026-02-07 06:37:55', '2026-02-07 06:34:32', '2026-02-07 06:37:55', NULL),
(5, '+256787842061', '$2y$12$pAgzKryt9RuIPgXpsr8SEuYJNVrKpKc/zmN.G5dXOZnt3HXXkRuYG', 'Musumba Jonathan', 'jmprossy@gmail.com', NULL, NULL, NULL, NULL, NULL, 'en', NULL, 'admin', 1, 1, 'approved', NULL, 1, '2026-01-26 22:27:52', '2026-02-07 12:16:42', '2026-02-07 12:16:42', NULL, NULL),
(9, '+256777978697', '$2y$12$aFs203PlW1Qe7G3elRXvI.7inJJuYAOr/97PUMSAnN9CxgDsQba4a', 'Sembera Christopher', 'sembera@gmail.com', NULL, NULL, NULL, NULL, NULL, 'en', 'assets/uploads/profiles/profile_697f34323347d.jpeg', 'farmer', NULL, 1, 'approved', NULL, 1, '2026-01-27 08:10:51', '2026-02-07 06:32:51', '2026-02-07 06:32:51', NULL, NULL);

--
-- Triggers `users`
--
DELIMITER $$
CREATE TRIGGER `audit_user_delete` BEFORE DELETE ON `users` FOR EACH ROW BEGIN
    INSERT INTO system_audit_log (event_type, user_id, entity_type, entity_id, old_data, ip_address)
    VALUES (
        'delete',
        @current_admin_id,
        'users',
        OLD.id,
        JSON_OBJECT(
            'full_name', OLD.full_name,
            'phone_number', OLD.phone_number,
            'user_type', OLD.user_type,
            'created_at', OLD.created_at
        ),
        @current_ip_address
    );
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `create_approval_request` AFTER INSERT ON `users` FOR EACH ROW BEGIN
    IF NEW.user_type IN ('buyer', 'extension_officer') THEN
        INSERT INTO user_approvals (user_id, user_type, approval_status)
        VALUES (NEW.id, NEW.user_type, 'pending');
        
        -- Update user approval status
        UPDATE users SET approval_status = 'pending' WHERE id = NEW.id;
        
        -- Notify admins
        INSERT INTO notifications (user_id, title, message, type, icon)
        SELECT 
            id,
            'New User Approval Request',
            CONCAT('New ', NEW.user_type, ' registration requires approval: ', NEW.full_name),
            'warning',
            'user-check'
        FROM users
        WHERE user_type = 'admin';
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `create_user_profile_on_registration` AFTER INSERT ON `users` FOR EACH ROW BEGIN
    INSERT INTO user_profiles (user_id) VALUES (NEW.id);
    INSERT INTO user_preferences (user_id) VALUES (NEW.id);
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `user_achievements`
--

CREATE TABLE `user_achievements` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `achievement_type` enum('verified_farmer','top_seller','helpful_member','early_adopter','community_leader','knowledge_sharer','market_expert','five_star_rated','active_contributor','sustainability_champion','innovation_leader') NOT NULL,
  `achievement_name` varchar(100) NOT NULL,
  `achievement_description` text DEFAULT NULL,
  `icon_url` varchar(255) DEFAULT NULL,
  `earned_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_approvals`
--

CREATE TABLE `user_approvals` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `user_type` enum('farmer','buyer','extension_officer','admin') NOT NULL,
  `approval_status` enum('pending','approved','rejected') DEFAULT 'pending',
  `supporting_documents` text DEFAULT NULL COMMENT 'JSON array of document URLs',
  `business_name` varchar(200) DEFAULT NULL COMMENT 'For buyers/organizations',
  `business_registration` varchar(100) DEFAULT NULL,
  `tax_id` varchar(50) DEFAULT NULL,
  `qualification_documents` text DEFAULT NULL COMMENT 'For extension officers',
  `rejection_reason` text DEFAULT NULL,
  `approved_by` int(11) DEFAULT NULL,
  `approved_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Triggers `user_approvals`
--
DELIMITER $$
CREATE TRIGGER `audit_approval_update` AFTER UPDATE ON `user_approvals` FOR EACH ROW BEGIN
    IF NEW.approval_status != OLD.approval_status THEN
        INSERT INTO system_audit_log (event_type, user_id, entity_type, entity_id, old_data, new_data, ip_address)
        VALUES (
            IF(NEW.approval_status = 'approved', 'approve', 'reject'),
            NEW.approved_by,
            'user_approvals',
            NEW.id,
            JSON_OBJECT('status', OLD.approval_status),
            JSON_OBJECT('status', NEW.approval_status, 'reason', NEW.rejection_reason),
            @current_ip_address
        );
    END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `notify_approval_status` AFTER UPDATE ON `user_approvals` FOR EACH ROW BEGIN
    IF NEW.approval_status != OLD.approval_status THEN
        IF NEW.approval_status = 'approved' THEN
            INSERT INTO notifications (user_id, title, message, type, icon)
            VALUES (
                NEW.user_id,
                'Account Approved',
                'Your account has been approved. You can now access all features.',
                'success',
                'check-circle'
            );
            
            -- Update user status
            UPDATE users 
            SET approval_status = 'approved', is_verified = 1 
            WHERE id = NEW.user_id;
            
        ELSEIF NEW.approval_status = 'rejected' THEN
            INSERT INTO notifications (user_id, title, message, type, icon)
            VALUES (
                NEW.user_id,
                'Account Rejected',
                CONCAT('Your account application was rejected. Reason: ', COALESCE(NEW.rejection_reason, 'Not specified')),
                'danger',
                'x-circle'
            );
            
            -- Update user status
            UPDATE users 
            SET approval_status = 'rejected' 
            WHERE id = NEW.user_id;
        END IF;
    END IF;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `user_blocks`
--

CREATE TABLE `user_blocks` (
  `id` int(11) NOT NULL,
  `blocker_id` int(11) NOT NULL,
  `blocked_id` int(11) NOT NULL,
  `reason` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_certifications`
--

CREATE TABLE `user_certifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `certification_name` varchar(200) NOT NULL,
  `issuing_organization` varchar(200) DEFAULT NULL,
  `issue_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `credential_id` varchar(100) DEFAULT NULL,
  `credential_url` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_education`
--

CREATE TABLE `user_education` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `institution` varchar(200) NOT NULL,
  `degree` varchar(100) DEFAULT NULL,
  `field_of_study` varchar(100) DEFAULT NULL,
  `start_year` year(4) DEFAULT NULL,
  `end_year` year(4) DEFAULT NULL,
  `grade` varchar(20) DEFAULT NULL,
  `description` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_encryption_keys`
--

CREATE TABLE `user_encryption_keys` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `public_key` text NOT NULL,
  `encrypted_private_key` text NOT NULL,
  `salt` varchar(255) NOT NULL,
  `iv` varchar(255) NOT NULL,
  `fingerprint` varchar(64) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `user_encryption_keys`
--

INSERT INTO `user_encryption_keys` (`id`, `user_id`, `public_key`, `encrypted_private_key`, `salt`, `iv`, `fingerprint`, `created_at`, `updated_at`) VALUES
(1, 3, '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAypwkUObT6WR0gULEcOlQ\n8IpesUK3LWNnaiqd6RyvV1FPVhZE63P3llJWTHdI9MDgdx5V0syjB3Uz3PWpc9Th\nTHeF5to5zTLZwqWb1Z8bB842ln/PT1FP5M8urdudqjx0ZlE+hs/aYdlF22jIEDin\n7OvXt1e+Hg2FKCqXSAlLWx/RDr1kDRPTiFLlVeFMpTFzC1poarETozSP5nGco3Ng\njEXUrohAMehxdvSAfxYaWv5HXZQWH3IpIzsEtg4ATD+GsBnyu15q+ZizSgY0M9Eu\nNGffcQYY0MmwAGuKJa9huO0+qR7YGgr3N4LkS821CCARoN2VRLdg1+GfaPqIlseh\nuwIDAQAB\n-----END PUBLIC KEY-----\n', 'RW5BcUs2QW1rNTBQMGVvUkpCVWFBVnpjYnZmSzVMRTEwWlptSmJyTDYybng4eEtjdG1pZytNMzJJaTBKdGRwM1o1ZFNCZ1RIbjRzTW93NlBESlFWcmc3dG5Wc2R4MXRGS0F6TFowUUhDdEJIRlR6eCtRZlNISHpZVE9yRDdweTV6SGFaL2h4Ry9NSHRtNHFJS2FTazN6YVlIT3pNUzVic2pLa3BOMGY5SlVnQ1FlbXdNeWhXZk5iZysvbWJJQStXQUtGYVJBV1BVSC9lQy95ME84VDIwbUpKZ0ZGR2YvWTVYZStXVzQxTVpoT1dBdWJRZ3NWZzRzbGx2bjhpcFlWOVpkSnlJVXVqUk9jT00vUUpVZ1FzcjZpbkZXU3RZUmY0b2IyZHBxWnJ4RmtGTGFheGM1UWRnZGJhWjR4L08vcDVJUk10Nm1sOXpIQ2dwdTRDaEowUThUd2lrNWl6a2N1TGpxTU5kMnBzRFd2SzNBZ1h2T0J5RlFCaGVVZVZHckZVWmd3bUFjdGRobldCaTlMRW42eHFxSHQ2aXkydmVtdGZrTTFLdVBYU3N1ZGRHcU1QUCsxbmEwOUh6bzBpMWtFU1hqTndiZFlpSTVRS2pTREZtaVNodWZuazV0K05rSGpVR0dPaXVuUjlsOE1CMkl6SDZYNnpGZnE2N3p0NHQrbjhiNWEzbzVRbnJkWmo0TjdvdWJEUUZPTE8xRDJ5OTVxbEtyZEl4TFBaQVRTOFV4K3NmdWZHdW1NOTh1VDJVZU1oNVo0MlVxdmZyU1YrWDFQdDA0MUxjUzBuN2prLzhmTXNtQmVjZXovTDhPVXRFL0JVQ3NBdjZYTlNkVVJqcDRpOG5VRlFwODBoeGRZaTd5NzY2dTZ6M3FDeWFlQU84Q3FZaUV5R1ZRejRGRDN2eDdWQ2s4VWFtNDhqbzNTWUdaYkkvY1BXcFh0dU9oRU1qZjdVSW5YZFQ5aWsvTGsrOHBpdlExWW5JeThPRjNSTGMrWVMrSlZoUmRhbWVXUS91bE5pVlZzOWtFSDlTdnl4Ky8rL2Z0WE4yejlTOWpuSllRc1ZGS1ZraGpnYUxLLzhpQTFiNnQyYlp2aXFUYkhOYWZnM1IycTd0UG9HOXpWWXY5Umtyd2h0WllLZHVmcDZaakdYK1FnVEJkMTNsVERoeHJReEllRnU2QXJJazVaS0trYmxhSzJqWUtZT0diTS91TVBvRjVJaGEzN1J5OUFnazBDL0FhUXl2MVZxa0o2dDZ3b3FSUUxyRlVIcDZQYmNqRWFzVDdzY1ZLM0NOQ3ZLZjFnWTZqRkx4SUdFaDFWL0ViQjVvVERpcDlaV2NOOXV3SnRuZlRHYnJyVDZsMTlZeDRYYnZDZEZnMGJuVjlNOEE5NzJVL21BWkU5OURDUjkzQUlwWEV6SFp0VW9VOXJYU1owcnlhZDRyajJ1dHVvRWNaWlRDRlBsWG83azJYck5Qdnk0enViMW5LbGtOTVJ0SUlGOUl2cHN0Q3dacjJEQmFQQjVQcjM5Um1oa21yOStnWlBRWFpPaVhqUElnYlpOelMxNEZPMzNGMnRVcE5CdTRGUGZTOEhtdXFVNTFmVVlSWnR6bXNMYkR5QUlqbS91U01FSWJTQ3pnUnhYYitoLzRWVnhtRXpWb2VYQUVFWTAwRVdzVDI5STZTbVJjVHdyZXhOWGxrYkMybjZnejZGTEF1dUhRbFptTU9iUzBvUWJrY0RrOE0vYmc2eFdKMjFBOFh0Q0lPZzcrN2hxb2NlNlVDeGo5OGRJR1g1S25ya0phVGUzQWdCcHRoRk9Lb1o5MktFV3ZzeEc1TXl0b00yRlF1am85MTR4d1pGTTQ1cWJ1TkYweW54S2cvM2dTanRoQUtzUFBCbE1BV3BjRGJaajh2eWRicUhPV3JDVTBtdkd3ZkprWjlyQk5pQ1F1M0Q1NWJvV0dyMWdBdXBLRXpSMnpQS1FxSlZtRU8rVWZBanF2OUE5ZGRCZGNYV1N4LzZvLzVYL1FPVFQ4SWF1L2NEbEpoYTFDc2FNMGRNZXFzTjlXUnNMbHo0c3drMHRtdWR5Zk9DZWVBTjdsbW1lMTlZRmhxcUVpUXZySXRQVlZ6cFlZTnVGb1dsS3VkRS9qN1EydElOeFhON3JBRVVSajZaTlY5TGJNQ1NMem1WWFVwM3ZnMENZRkRiSlRGUk0reU5yZGZ1aXROeHN2K281bzJqRHpkYzRsZHhSVk5aVDVzZ3lwMnl6WkJjdkhkcHNaTEd5bkVnSHJKblBDWWc4V2hQL1EzMTVrUE8wMFk1SnhWS3RadXhQd0dhYktsUkxBd2w4WUdyblJYM0ZXbEl0VFFNN3pZMGRqMkhkS1daM2lYMWdrbXBXbTVpZ0duTXQ1d0s1blhoTnVUTHBLQ0FWTmNRMFljMW5PWFpoWExkc28zQ21sNi9mamRqQS9lV2hERDBGSGZvOWVVd29mclF1QzBqOVlvNWxjMmw0MzRraVQ2SWpWM245UkVuUTZnRWJJcDloYlk4eGJFUk9RaGUxeDJFeFl3VFpWbkFSZjlBZTRiVzl2STQ5c0xqeVhSVlZ5bW9UZXI1V3Z4RGIycVM5ZkhuTXJnVFVJdkRjN2g5NDZreDVTVkZLK0lGODJFaUllbGVtZ29MYWhrVU1la3FHVFgzMmszMGhKeHlPRHBXSSs1OU9UZHpTRVRFRXVMTXNEWWl1MUJEbnBWMzVvWkZkaURGK01ad0NhUFFYeDNtYmgydjJJSFAxNXo3d1hhRGVjT1YxTzR5d3ZQVVIzemliTkRTdG8rV0kzUXBjV3NZc3pIbEJBV21ZMHZ5SmtBSGgyRlU2K3N4bi85Qk9ld0VnbU5wb2pJcXU0WkxGNHFCQVNybEdWcEc4Q3cyaXp2azdwajUwZEt6RnVXL3hHT21HZmVDbVN2Y1BKakdPUExnVXYxaDdKWmlZaStkNGhkOGxuU2E4bFVCdWszYk5JWkgzTkVIeVFDK3VpY29jcWJoWUxFSTFrU2ZQM1pXbTh3ekFtcVNDa21yUUJNcDdpU0dkZkE0PQ==', 'BpztC9vNTUbsFAZY+4Mw++uAXEbymWQTK5tnzU3LqLU=', 'XacHspAiTw/faFKvqAeWfw==', 'cb5a460756112d0e9321a7b0227bea50b02faabbb6951032add9dedfd5395748', '2026-02-07 06:22:35', '2026-02-07 06:22:35'),
(2, 9, '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqTXoH4HAkQRjVzZ8y4nV\nSjhH1OKIA7ij3ul6X0yOU5wMJ7PFAYZf8UkIdLgIVUHMPp4wO+pPNQl1ltxCjYqw\nPz94CJiDd1SqkGyFIPYmnC3QSHMRULxR7g60WDo7irN/euNt/Sky2iT7eWraRGyB\nAOlHo3tuNhwYS74t3ZdmKA0pWcKNwakn//VyY3PMw7edz/JqI6s/Aq5a6exTX5DP\n3FnFApC0acLlL0h6YGto/3AbunJg1BvDW9LtNayD/0WQTzZZ7tTcdxJqwjfnQV89\nBEy5nAa6YZBVQcBp6Xvw4SY45f31eywmy6lopldZtkI1aReLSYxiB6aq415dfTmE\nXwIDAQAB\n-----END PUBLIC KEY-----\n', 'eW5lN0JOWHBSbHZjaDh6TXBuSWdRK2VBcW5MY0VYQ2Zmc0p6OTI5U296YVRyWHROVWlDOTFtSm1Vd042MjBlZDlmNXdhWjM5WmE0NEk5UFpUbXhUQ0RvS2JqdEFuVVJCRFBCZFlaZGNrVGtVNXBpcnhNTmdkbE9OekR6TVJIejdEbFgwMm1PNVYyY0xtWXdrbXEweUUxNS9BbFhNWVFzdjRjMGtyOEFBajNmbERRbndHV3JlZWhFUnFBbU9aRDF3UkNQdS93amhvUnR5eUxhckh4MVFOcVJ0cG5mUEJLNmNXbWFuRDZtcXRXNDU5bXR6SzhXS0ExVHE0dVlHTGwrUDhUMmhZTmxkdCtmQVJ6eFl4S05DU08zUnd0MjhXUnozZGdlMVg2QkhtNFI1Ni9IcmNuQUdwbUVQSzFtdzd2VVR0aXloc0ZHTzVRekJJeTNBLzJvY2Ura2VJeUxHYXc1U21kbStKM1RXdGpiRlRIS0l1UHVtUUJ6VC9JQjVGcFpqN3BreG5XaEVqWWx4WWlZbU8zOU9neXl4ZFBaZFFKa0JUK3k0akdnSXVRT3VKVjY0RjI2dWZxd1M2Y1I1dUNyM2lLOEtjUEhodnhuOHN0Ym9hWGJqTWh5dHUxSEZVQkQwWnZudWZvUUtpak5udDV5dDhnVytQcnhCOXo3TVd3ZDNCNHRGUlJ4ZjR5VGhidys3M3kyOEhWcU1IY3FsdW9yTmZNaVVsQUpOT1NOQkFUNDRraVBpd0V1VTJxVzFxeDhSVFJ1TmN4d1c2UkxsdE5nbWJuZmUrMmJpdy9IbVJlUm9NY2VNN1hSZDgxMWdXRnp5YWtxQ2R5TDR0ZlMwM3RoSlNYVE9BdlJDSllIM2tmRWlIYWFnVnREQVVhcUJtdFYyZm4rbTVRbUdxc0xzUjBRWElpRTJ3S2VNaHBYdDkyMkF6NlNvTVZOT3BUWi9UUkpvLzErU0pWUmFzdXhmaWFpQjVXZ1NVTHNjTFdPeC8zM3BFcElmZ0NmQzdNTHJiNWM0em5YdUMzak1qeUhESE03R1l0bERBT0ppNXhLa2ZQL2NxS0x1UWFyQ3lUZUcwdUNDM3czZnEraFBHSDh3cHkzeXNlZDdCc28rMTRKVlhJT2dmeDFIbFp6S3daWVVEQWszWVRCNEdIbFhxb1phM3cvRnhaMDdCRFBYN1M4RTYyL0JHZ2RpY1hrRFhNVTF1eEc5U0kyR3NxRnJDR3hRTW5HMWgxenF6d2tsR1BBVWMya0tyOVdFbnVrVFc1aXVXa3o2dW0yeldCU0tPVjk0dU1JVVVlTlo1NE4zSUJid09sdEhPODZkVzlqYkxWSEttNEFDSzVlRjZkZ2pXd1g0N1VzdXRtK0RhaFpKbTg5YjNPb3c5bVFVMHNRM1RxN3ROQ2VMNDIrK2Z4d3JSQldMbDJZeWYyNlRGT1JNSlMwK3pndXdQeTRxMzRMcDFjWlBzeEkxVEozQ2RWVVV4ZFFuaWJqN0ROWW1PSGxnRC8vSlphME5jeVBYTVNORktxd1ZnaTRrWUEzWndybXlybVdxMkxsaGdSZ0w0c3dra3huZTUvTmI0WkwwUXhFRFFWZ0FEZGMvMGY5cDErRWxLL3Z0WWJnTjlvSXU2UUx3aHZ5RkFhVUh6MVg2SmMwN202c0xYSUxoYXYxb21wTnVPallicU1TKys2N3VaK01sSUkyV3NKNDBuaVZsWmNuSTlrZzdLVkhxM1U3cU1kYXBUU2pUaGZ2UDlXNHNRblV0czJ5ZmYxTHAwU0NnaTJFOWVkVys4eDZhT0ErMjhPQk5rMVlhQTBpWDlLaFh4RWovYUNsNU5zMEppbExkb09KNUM0MENINkFnUlF1emtxZmQ2RHFmdWEySzJ5K0lkeHliRlR6V3dlNTVQOFRzU1Mxb1NMc3JZLy80TVdvMHJ3ZC9mdWd3L1lYcmtEeE9SZHJiU0lYRFYxRGJZRlRSTGVNMDU5WGhsVmtpNHI1Ulp2MHdwUGlQSEd5Y0RQVTdVNmU2MjlZMENtYVRXSVpxS1Zya2gzS1BIM2dFNms2Vlk4Z2hQbmdSNFBrV1hGWUNPc3hJUUZkZStCZEZ3Q21oZ0RRUElIQlcrNWRUcEwxRzk1MEJ5bEs1UFJnYU5jYzBpYUJhay9uYW9ReVRmVWxjUXl6NTd5VWFFZm1waS9MeDd0aTEzbnh2LytpNjhzRVQ2ODhDNTdkWDFwK2dndzRTei9CREt4Smo0R1Q2bnUvS1MxMFQ1azdwa1k0akNkMytuTXdIR1dVVktKYmV1SGhsR2pWU3hOcnV2MkZKRmt5RXBuTUM4OGxoUlozaG9PS0duNHFVMDFpMkpPUWJ4c3k1a2thWEsyK0Y5VWhYWHNtaW5EaHN1Y2RTUHQwWUJiTGdGc0JST2VOUEo5cFhQVFZDUkI4MkpJSWFEUjh4aTN1QVBaYnZTV2hKTVlBVE9BZ0pQbnF4Y1ZtN3hmeUJDVjZnY2hxS00vU2Iyd2x5d3Zha1ovdWVwNnNwQVlwVmJTTVpuK3FEdlJQRWVOZGJRQldpZ2tIem1sMnlSYkZVenZ2VlRGQmF1dkFUV0U5VEdCbjFUSXlveERCMVRiSU9hdG9BOTFSdGNZenpJajkzR050Q2ZIVEJOSHRpMk54dC9XUzZVYXoyRk9hdTJ1MEViTkNoU1kxUSthNCtoYUNQeVVBb04zWDd6dCsyU3U1TEFhQmlKY3JuV2J2OUVBWFFZS3NDTUZlK2hIVnJmdTdJSGdNU2RXcjczdGZIM1h4alhPdFY3VDdqTkdDR2ZSaTd0MzFVbk9NYlg1Um9UdklJZUVSVStUNmZEVlpGVjlkNzZWR09HbFczd01IWjVuQ0NyZzNsQ1N1K1YzcnFaOGFoNzR1R205cEdLaE5TZTBySzMyaktvSUkwck5YRzhaNWFwT3MrQ2RKZjJ2aVBvTTlpR1J0OE5TeHNBMlc2ZUZET0IrQk9hMkRCeXg2NHJSdDA0UjVOWDgyLzN4aG9ibUFpSVRnVHBiMUEzWlRNaHFpdkt1UlZXeVRkeVBvPQ==', 'YTcnvMi0rg8zXQpiBMADwucbkrcxi4qSRJl3x1407qk=', 'PvC1rpjM+Ang4Vc75kctgw==', '0d5af46b7b2923a14e24dc89569f5e69f7bbe287abaf6a254a58d66fac4820de', '2026-02-07 06:27:49', '2026-02-07 06:27:49');

-- --------------------------------------------------------

--
-- Table structure for table `user_experience`
--

CREATE TABLE `user_experience` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `organization` varchar(200) DEFAULT NULL,
  `location` varchar(100) DEFAULT NULL,
  `start_date` date DEFAULT NULL,
  `end_date` date DEFAULT NULL,
  `is_current` tinyint(1) DEFAULT 0,
  `description` text DEFAULT NULL,
  `employment_type` enum('full_time','part_time','contract','volunteer','self_employed') DEFAULT 'full_time'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_farming_reminders`
--

CREATE TABLE `user_farming_reminders` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `enterprise_id` int(11) DEFAULT NULL,
  `schedule_id` int(11) DEFAULT NULL,
  `title` varchar(200) NOT NULL,
  `description` text DEFAULT NULL,
  `reminder_date` date NOT NULL,
  `reminder_time` time DEFAULT NULL,
  `activity_type` enum('land_preparation','planting','weeding','fertilization','pest_control','irrigation','harvesting','post_harvest','custom') DEFAULT 'custom',
  `is_recurring` tinyint(1) DEFAULT 0,
  `recurrence_pattern` varchar(50) DEFAULT NULL COMMENT 'daily, weekly, monthly',
  `status` enum('pending','completed','missed','cancelled') DEFAULT 'pending',
  `completed_at` timestamp NULL DEFAULT NULL,
  `notification_sent` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_life_events`
--

CREATE TABLE `user_life_events` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `event_type` enum('started_farming','harvested','award','certification','land_acquired','business_started','other') NOT NULL,
  `event_title` varchar(200) NOT NULL,
  `event_description` text DEFAULT NULL,
  `event_date` date DEFAULT NULL,
  `visibility` enum('public','friends','private') DEFAULT 'public',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_preferences`
--

CREATE TABLE `user_preferences` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `email_notifications` tinyint(1) DEFAULT 1,
  `sms_notifications` tinyint(1) DEFAULT 1,
  `push_notifications` tinyint(1) DEFAULT 1,
  `friend_request_notifications` tinyint(1) DEFAULT 1,
  `message_notifications` tinyint(1) DEFAULT 1,
  `post_notifications` tinyint(1) DEFAULT 1,
  `who_can_see_posts` enum('public','friends','private') DEFAULT 'friends',
  `who_can_contact` enum('everyone','friends','none') DEFAULT 'everyone',
  `who_can_see_friends` enum('everyone','friends','private') DEFAULT 'everyone',
  `preferred_language` varchar(10) DEFAULT 'en',
  `theme` enum('light','dark','auto') DEFAULT 'light',
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_profiles`
--

CREATE TABLE `user_profiles` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `bio` text DEFAULT NULL COMMENT 'Short biography',
  `tagline` varchar(200) DEFAULT NULL COMMENT 'Professional tagline/headline',
  `about_me` text DEFAULT NULL COMMENT 'Detailed about section',
  `date_of_birth` date DEFAULT NULL,
  `gender` enum('male','female','other','prefer_not_to_say') DEFAULT NULL,
  `cover_photo` varchar(255) DEFAULT NULL,
  `secondary_phone` varchar(15) DEFAULT NULL,
  `whatsapp_number` varchar(15) DEFAULT NULL,
  `website` varchar(255) DEFAULT NULL,
  `occupation` varchar(100) DEFAULT NULL,
  `education_level` enum('primary','secondary','certificate','diploma','degree','masters','phd') DEFAULT NULL,
  `years_in_farming` int(11) DEFAULT 0,
  `farm_size_acres` decimal(10,2) DEFAULT 0.00,
  `farming_type` enum('subsistence','commercial','mixed','organic') DEFAULT 'mixed',
  `facebook_url` varchar(255) DEFAULT NULL,
  `twitter_url` varchar(255) DEFAULT NULL,
  `instagram_url` varchar(255) DEFAULT NULL,
  `linkedin_url` varchar(255) DEFAULT NULL,
  `youtube_url` varchar(255) DEFAULT NULL,
  `interests` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of farming interests' CHECK (json_valid(`interests`)),
  `skills` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of farming skills/specializations' CHECK (json_valid(`skills`)),
  `languages` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of spoken languages' CHECK (json_valid(`languages`)),
  `crops_grown` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of crops currently growing' CHECK (json_valid(`crops_grown`)),
  `livestock_kept` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Array of livestock types' CHECK (json_valid(`livestock_kept`)),
  `show_phone` tinyint(1) DEFAULT 1,
  `show_location` tinyint(1) DEFAULT 1,
  `show_email` tinyint(1) DEFAULT 1,
  `show_birthday` tinyint(1) DEFAULT 0,
  `allow_messages` tinyint(1) DEFAULT 1,
  `allow_friend_requests` tinyint(1) DEFAULT 1,
  `profile_visibility` enum('public','friends','private') DEFAULT 'public',
  `profile_views` int(11) DEFAULT 0,
  `profile_completeness` int(11) DEFAULT 0 COMMENT 'Percentage 0-100',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `user_profiles`
--

INSERT INTO `user_profiles` (`id`, `user_id`, `bio`, `tagline`, `about_me`, `date_of_birth`, `gender`, `cover_photo`, `secondary_phone`, `whatsapp_number`, `website`, `occupation`, `education_level`, `years_in_farming`, `farm_size_acres`, `farming_type`, `facebook_url`, `twitter_url`, `instagram_url`, `linkedin_url`, `youtube_url`, `interests`, `skills`, `languages`, `crops_grown`, `livestock_kept`, `show_phone`, `show_location`, `show_email`, `show_birthday`, `allow_messages`, `allow_friend_requests`, `profile_visibility`, `profile_views`, `profile_completeness`, `created_at`, `updated_at`) VALUES
(1, 3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0.00, 'mixed', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, 0, 1, 1, 'public', 0, 0, '2026-02-01 18:00:58', '2026-02-01 18:00:58'),
(2, 9, 'Passionate Developer', 'Senior IT', '', '1993-01-21', 'male', NULL, '07586973337', '0777115678', 'https://ilabstech.com', 'IT officer', 'degree', 0, 0.00, 'mixed', '', '', '', '', NULL, '[\"Computer Programming\"]', '[\"Python and PHP development\"]', NULL, NULL, NULL, 1, 1, 1, 0, 1, 1, 'public', 1, 68, '2026-02-01 18:00:58', '2026-02-01 18:32:12'),
(3, 4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0.00, 'mixed', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, 0, 1, 1, 'public', 0, 0, '2026-02-01 18:00:58', '2026-02-01 18:00:58'),
(4, 2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0.00, 'mixed', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, 0, 1, 1, 'public', 0, 0, '2026-02-01 18:00:58', '2026-02-01 18:00:58'),
(5, 5, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0.00, 'mixed', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, 0, 1, 1, 'public', 0, 0, '2026-02-01 18:00:58', '2026-02-01 18:00:58');

--
-- Triggers `user_profiles`
--
DELIMITER $$
CREATE TRIGGER `update_profile_completeness` BEFORE UPDATE ON `user_profiles` FOR EACH ROW BEGIN
    DECLARE completeness INT DEFAULT 0;
    
    -- Base profile (20%)
    IF NEW.bio IS NOT NULL AND NEW.bio != '' THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.tagline IS NOT NULL AND NEW.tagline != '' THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.about_me IS NOT NULL AND NEW.about_me != '' THEN
        SET completeness = completeness + 10;
    END IF;
    
    -- Contact info (15%)
    IF NEW.whatsapp_number IS NOT NULL AND NEW.whatsapp_number != '' THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.secondary_phone IS NOT NULL AND NEW.secondary_phone != '' THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.website IS NOT NULL AND NEW.website != '' THEN
        SET completeness = completeness + 5;
    END IF;
    
    -- Professional info (25%)
    IF NEW.occupation IS NOT NULL AND NEW.occupation != '' THEN
        SET completeness = completeness + 8;
    END IF;
    
    IF NEW.education_level IS NOT NULL THEN
        SET completeness = completeness + 7;
    END IF;
    
    IF NEW.years_in_farming > 0 THEN
        SET completeness = completeness + 10;
    END IF;
    
    -- Photos (15%)
    IF (SELECT COUNT(*) FROM profile_photos WHERE user_id = NEW.user_id AND photo_type = 'profile' AND is_current = 1) > 0 THEN
        SET completeness = completeness + 8;
    END IF;
    
    IF NEW.cover_photo IS NOT NULL AND NEW.cover_photo != '' THEN
        SET completeness = completeness + 7;
    END IF;
    
    -- Social & Skills (15%)
    IF NEW.interests IS NOT NULL THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.skills IS NOT NULL THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF NEW.facebook_url IS NOT NULL OR NEW.twitter_url IS NOT NULL OR NEW.instagram_url IS NOT NULL THEN
        SET completeness = completeness + 5;
    END IF;
    
    -- Additional info (10%)
    IF NEW.date_of_birth IS NOT NULL THEN
        SET completeness = completeness + 5;
    END IF;
    
    IF (SELECT COUNT(*) FROM user_experience WHERE user_id = NEW.user_id) > 0 THEN
        SET completeness = completeness + 5;
    END IF;
    
    SET NEW.profile_completeness = completeness;
END
$$
DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `user_recommendations`
--

CREATE TABLE `user_recommendations` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL COMMENT 'User being recommended',
  `recommender_id` int(11) NOT NULL COMMENT 'User giving recommendation',
  `recommendation_text` text NOT NULL,
  `relationship` varchar(100) DEFAULT NULL COMMENT 'How they know each other',
  `status` enum('pending','approved','declined') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_reports`
--

CREATE TABLE `user_reports` (
  `id` int(11) NOT NULL,
  `reporter_id` int(11) NOT NULL,
  `reported_user_id` int(11) NOT NULL,
  `chat_id` int(11) DEFAULT NULL,
  `report_type` enum('spam','harassment','fake_profile','inappropriate_content','scam','other') NOT NULL,
  `description` text DEFAULT NULL,
  `evidence_urls` text DEFAULT NULL COMMENT 'JSON array of screenshot URLs',
  `status` enum('pending','reviewing','resolved','dismissed') DEFAULT 'pending',
  `admin_notes` text DEFAULT NULL,
  `reviewed_by` int(11) DEFAULT NULL,
  `reviewed_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_saved_items`
--

CREATE TABLE `user_saved_items` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `item_type` enum('product','post','tip','user_profile','group','event') NOT NULL,
  `item_id` int(11) NOT NULL,
  `collection_name` varchar(100) DEFAULT 'Saved Items',
  `notes` text DEFAULT NULL,
  `saved_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `user_stories`
--

CREATE TABLE `user_stories` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `media_type` enum('image','video','text') NOT NULL,
  `media_url` varchar(255) DEFAULT NULL,
  `content` text DEFAULT NULL,
  `views_count` int(11) DEFAULT 0,
  `expires_at` timestamp NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `user_stories`
--

INSERT INTO `user_stories` (`id`, `user_id`, `media_type`, `media_url`, `content`, `views_count`, `expires_at`, `created_at`) VALUES
(1, 9, 'image', 'http://localhost/aims/assets/uploads/stories/story_6986334791467_1770402631.jpg', 'Fresh from the garden', 1, '2026-02-07 18:30:31', '2026-02-06 18:30:31'),
(2, 9, 'image', 'http://localhost/aims/assets/uploads/stories/story_6986334bb84d6_1770402635.jpg', 'Fresh from the garden', 1, '2026-02-07 18:30:35', '2026-02-06 18:30:35');

-- --------------------------------------------------------

--
-- Table structure for table `villages`
--

CREATE TABLE `villages` (
  `id` int(11) NOT NULL,
  `parish_id` int(11) NOT NULL,
  `village_name` varchar(100) NOT NULL,
  `village_code` varchar(10) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `villages`
--

INSERT INTO `villages` (`id`, `parish_id`, `village_name`, `village_code`, `created_at`) VALUES
(1, 103, 'Budhabangula A', 'BDB-A', '2026-01-27 22:12:50'),
(2, 103, 'Budhabangula B', 'BDB-B', '2026-01-27 22:12:50'),
(3, 103, 'Kibuutu', 'KBT', '2026-01-27 22:12:50'),
(4, 104, 'Bugonyoka A', 'BGY-A', '2026-01-27 22:12:50'),
(5, 104, 'Bugonyoka B', 'BGY-B', '2026-01-27 22:12:50'),
(6, 104, 'Buzaaya', 'BZY', '2026-01-27 22:12:50'),
(7, 104, 'Nakisenyi A', 'NKS-A', '2026-01-27 22:12:50'),
(8, 104, 'Nakisenyi B', 'NKS-B', '2026-01-27 22:12:50'),
(9, 105, 'Bugabula A', 'BGB-A', '2026-01-27 22:12:50'),
(10, 105, 'Bugabula B', 'BGB-B', '2026-01-27 22:12:50'),
(11, 105, 'Bukendi', 'BKD', '2026-01-27 22:12:50'),
(12, 105, 'Nabitama A', 'NBT-A', '2026-01-27 22:12:50'),
(13, 105, 'Nabitama B', 'NBT-B', '2026-01-27 22:12:50'),
(14, 106, 'Buwaiswa', 'BWS', '2026-01-27 22:12:50'),
(15, 106, 'Kamwirungu A', 'KMW-A', '2026-01-27 22:12:50'),
(16, 106, 'Kamwirungu B', 'KMW-B', '2026-01-27 22:12:50'),
(17, 107, 'Buseete', 'BST', '2026-01-27 22:12:50'),
(18, 107, 'Buyunze A', 'BYZ-A', '2026-01-27 22:12:50'),
(19, 107, 'Buyunze B', 'BYZ-B', '2026-01-27 22:12:50'),
(20, 107, 'Nakabugu A', 'NKB-A', '2026-01-27 22:12:50'),
(21, 107, 'Nakabugu B', 'NKB-B', '2026-01-27 22:12:50'),
(22, 108, 'Bulike', 'BLK', '2026-01-27 22:12:50'),
(23, 108, 'Busala', 'BSL', '2026-01-27 22:12:50'),
(24, 108, 'Kasozi', 'KSZ', '2026-01-27 22:12:50'),
(25, 108, 'Namalemba', 'NML', '2026-01-27 22:12:50'),
(26, 109, 'Bunafu A', 'BNF-A', '2026-01-27 22:12:50'),
(27, 109, 'Bunafu B', 'BNF-B', '2026-01-27 22:12:50'),
(28, 109, 'Nabisira', 'NBS', '2026-01-27 22:12:50'),
(29, 109, 'Nawanyago', 'NWG', '2026-01-27 22:12:50'),
(30, 110, 'Buwutu', 'BWT', '2026-01-27 22:12:50'),
(31, 110, 'Ikumbya', 'IKM', '2026-01-27 22:12:50'),
(32, 110, 'Nsambya', 'NSM', '2026-01-27 22:12:50'),
(33, 110, 'Wandago', 'WND', '2026-01-27 22:12:50'),
(34, 111, 'Budhuuba A', 'BDH-A', '2026-01-27 22:12:50'),
(35, 111, 'Budhuuba B', 'BDH-B', '2026-01-27 22:12:50'),
(36, 111, 'Bugambo', 'BGM', '2026-01-27 22:12:50'),
(37, 111, 'Inula', 'INL', '2026-01-27 22:12:50'),
(38, 112, 'Bugonza', 'BGZ', '2026-01-27 22:12:50'),
(39, 112, 'Kawanga', 'KWG', '2026-01-27 22:12:50'),
(40, 112, 'Nantamali', 'NTM', '2026-01-27 22:12:50'),
(41, 112, 'Nawaka A', 'NWK-A', '2026-01-27 22:12:50'),
(42, 112, 'Nawaka B', 'NWK-B', '2026-01-27 22:12:50'),
(43, 112, 'Nawaka C (Buyego)', 'NWK-C', '2026-01-27 22:12:50'),
(44, 113, 'Bukobbo', 'BKB', '2026-01-27 22:12:50'),
(45, 113, 'Bulike', 'BLK', '2026-01-27 22:12:50'),
(46, 113, 'Idoome East', 'IDM-E', '2026-01-27 22:12:50'),
(47, 113, 'Idoome West', 'IDM-W', '2026-01-27 22:12:50'),
(48, 113, 'Nabitende', 'NBT', '2026-01-27 22:12:50'),
(49, 113, 'Ntayigirwa', 'NTY', '2026-01-27 22:12:50'),
(50, 114, 'Budhumbwire', 'BDW', '2026-01-27 22:12:50'),
(51, 114, 'Busimawu Zone', 'BSM', '2026-01-27 22:12:50'),
(52, 114, 'Waigugwe Zone', 'WGW', '2026-01-27 22:12:50'),
(53, 10, 'Bukabooli Zone', 'BKB', '2026-01-27 22:12:50'),
(54, 10, 'Busonga Zone', 'BSG', '2026-01-27 22:12:50'),
(55, 116, 'Mbogo Zone', 'MBG', '2026-01-27 22:12:50'),
(56, 116, 'Nawamwena', 'NWM', '2026-01-27 22:12:50'),
(57, 116, 'Nawansudde Zone', 'NWS', '2026-01-27 22:12:50'),
(58, 117, 'Kiyunga Central Zone', 'KYC', '2026-01-27 22:12:50'),
(59, 117, 'Kiyunga Hospital Zone', 'KYH', '2026-01-27 22:12:50'),
(60, 117, 'Kiyunga Industrial zone', 'KYI', '2026-01-27 22:12:50'),
(61, 118, 'Buwambuzi', 'BWZ', '2026-01-27 22:12:50'),
(62, 118, 'Lwanda', 'LWD', '2026-01-27 22:12:50'),
(63, 118, 'Ntandagwe', 'NTD', '2026-01-27 22:12:50'),
(64, 98, 'Budondo A', 'BDD-A', '2026-01-27 22:12:51'),
(65, 98, 'Budondo B', 'BDD-B', '2026-01-27 22:12:51'),
(66, 98, 'Bugoba', 'BGB', '2026-01-27 22:12:51'),
(67, 98, 'Kimanto A', 'KMT-A', '2026-01-27 22:12:51'),
(68, 98, 'Kimanto B', 'KMT-B', '2026-01-27 22:12:51'),
(69, 99, 'Bugogo', 'BGG', '2026-01-27 22:12:51'),
(70, 99, 'Bukaade', 'BKD', '2026-01-27 22:12:51'),
(71, 99, 'Bukwanga', 'BKW', '2026-01-27 22:12:51'),
(72, 99, 'Buwologoma Central', 'BWL', '2026-01-27 22:12:51'),
(73, 99, 'Katalakabi', 'KTL', '2026-01-27 22:12:51'),
(74, 99, 'Nabinoni', 'NBN', '2026-01-27 22:12:51'),
(75, 99, 'Nakamini', 'NKM', '2026-01-27 22:12:51'),
(76, 99, 'Ndhoya A', 'NDH-A', '2026-01-27 22:12:51'),
(77, 99, 'Ndhoya B', 'NDH-B', '2026-01-27 22:12:51'),
(78, 100, 'Bighunu', 'BGH', '2026-01-27 22:12:51'),
(79, 100, 'Bulonde', 'BLD', '2026-01-27 22:12:51'),
(80, 100, 'Busandha', 'BSD', '2026-01-27 22:12:51'),
(81, 100, 'Kiroba-Budoma', 'KRB', '2026-01-27 22:12:51'),
(82, 100, 'Kisimba', 'KSM', '2026-01-27 22:12:51'),
(83, 100, 'Nawantale', 'NWT', '2026-01-27 22:12:51'),
(84, 101, 'Budoma A', 'BDM-A', '2026-01-27 22:12:51'),
(85, 101, 'Budoma B', 'BDM-B', '2026-01-27 22:12:51'),
(86, 101, 'Budoma C', 'BDM-C', '2026-01-27 22:12:51'),
(87, 101, 'Bunhirira', 'BNH', '2026-01-27 22:12:51'),
(88, 101, 'Nabubya A', 'NBB-A', '2026-01-27 22:12:51'),
(89, 101, 'Nabubya B', 'NBB-B', '2026-01-27 22:12:51'),
(90, 101, 'Nakabondo', 'NKB', '2026-01-27 22:12:51'),
(91, 102, 'Bukanga-Bukendi', 'BKB', '2026-01-27 22:12:51'),
(92, 102, 'Bulwasira', 'BWS', '2026-01-27 22:12:51'),
(93, 102, 'Bumanha A', 'BMH-A', '2026-01-27 22:12:51'),
(94, 102, 'Bumanha B', 'BMH-B', '2026-01-27 22:12:51'),
(95, 102, 'Bumanha Central', 'BMH-C', '2026-01-27 22:12:51'),
(96, 102, 'Kantenga', 'KTG', '2026-01-27 22:12:51'),
(97, 102, 'Namukubembe A', 'NMK-A', '2026-01-27 22:12:51'),
(98, 102, 'Namukubembe B', 'NMK-B', '2026-01-27 22:12:51'),
(99, 119, 'Bulanga Estate', 'BLE', '2026-01-27 22:12:51'),
(100, 119, 'Kasokoso', 'KSK', '2026-01-27 22:12:51'),
(101, 119, 'Kataike', 'KTK', '2026-01-27 22:12:51'),
(102, 119, 'Kiwumbi', 'KWM', '2026-01-27 22:12:51'),
(103, 120, 'Bugwanala A', 'BGW-A', '2026-01-27 22:12:51'),
(104, 120, 'Bugwanala B', 'BGW-B', '2026-01-27 22:12:51'),
(105, 120, 'Itwe', 'ITW', '2026-01-27 22:12:51'),
(106, 120, 'Tagoole', 'TGL', '2026-01-27 22:12:51'),
(107, 121, 'Budhebera', 'BDB', '2026-01-27 22:12:51'),
(108, 121, 'Kyankuzi', 'KYK', '2026-01-27 22:12:51'),
(109, 121, 'Mufuwa', 'MFW', '2026-01-27 22:12:51'),
(110, 121, 'Nabukalu', 'NBK', '2026-01-27 22:12:51'),
(111, 122, 'Abalawuwe', 'ABL', '2026-01-27 22:12:51'),
(112, 122, 'Lumbuye', 'LMB', '2026-01-27 22:12:51'),
(113, 122, 'Luswiga', 'LSW', '2026-01-27 22:12:51'),
(114, 122, 'Nantamu', 'NTM', '2026-01-27 22:12:51'),
(115, 123, 'Kisansa', 'KSS', '2026-01-27 22:12:51'),
(116, 123, 'Luwangula', 'LWG', '2026-01-27 22:12:51'),
(117, 123, 'Walibo', 'WLB', '2026-01-27 22:12:51'),
(118, 123, 'Walibo Lulenzi', 'WLL', '2026-01-27 22:12:51'),
(119, 124, 'Botondola B', 'BTB', '2026-01-27 22:12:51'),
(120, 124, 'Busalamu Central', 'BSC', '2026-01-27 22:12:51'),
(121, 124, 'Butondolo A', 'BTA', '2026-01-27 22:12:51'),
(122, 124, 'Kidyope', 'KDY', '2026-01-27 22:12:51'),
(123, 125, 'Busiringe A', 'BSR-A', '2026-01-27 22:12:51'),
(124, 125, 'Busiringe B', 'BSR-B', '2026-01-27 22:12:51'),
(125, 125, 'Kiringo A', 'KRG-A', '2026-01-27 22:12:51'),
(126, 125, 'Kiringo B', 'KRG-B', '2026-01-27 22:12:51'),
(127, 126, 'Kigulamo A', 'KGL-A', '2026-01-27 22:12:51'),
(128, 126, 'Kigulamo B', 'KGL-B', '2026-01-27 22:12:51'),
(129, 126, 'Lukunhu A', 'LKH-A', '2026-01-27 22:12:51'),
(130, 126, 'Lukunhu B', 'LKH-B', '2026-01-27 22:12:51'),
(131, 127, 'Lukotaime A', 'LKT-A', '2026-01-27 22:12:51'),
(132, 127, 'Lukotaime B', 'LKT-B', '2026-01-27 22:12:51'),
(133, 127, 'Lukotaime C', 'LKT-C', '2026-01-27 22:12:51'),
(134, 127, 'Lukotaime D', 'LKT-D', '2026-01-27 22:12:51'),
(135, 128, 'Bufumba', 'BFM', '2026-01-27 22:12:51'),
(136, 128, 'Buwala', 'BWL', '2026-01-27 22:12:51'),
(137, 128, 'Gansembye', 'GSB', '2026-01-27 22:12:51'),
(138, 128, 'Iganga A', 'IGA-A', '2026-01-27 22:12:51'),
(139, 128, 'Iganga B', 'IGA-B', '2026-01-27 22:12:51'),
(140, 128, 'Irongo', 'IRG', '2026-01-27 22:12:51'),
(141, 128, 'Naimuli A', 'NML-A', '2026-01-27 22:12:51'),
(142, 128, 'Naimuli B', 'NML-B', '2026-01-27 22:12:51'),
(143, 128, 'Nsirira', 'NSR', '2026-01-27 22:12:51'),
(144, 129, 'Bukyamata', 'BKY', '2026-01-27 22:12:51'),
(145, 129, 'Kalyowa A', 'KLY-A', '2026-01-27 22:12:51'),
(146, 129, 'Kalyowa B', 'KLY-B', '2026-01-27 22:12:51'),
(147, 129, 'Kigunga', 'KGG', '2026-01-27 22:12:51'),
(148, 130, 'Kantenga', 'KTG', '2026-01-27 22:12:51'),
(149, 130, 'Kibinga A', 'KBG-A', '2026-01-27 22:12:51'),
(150, 130, 'Kibinga B', 'KBG-B', '2026-01-27 22:12:51'),
(151, 130, 'Nakavuma', 'NKV', '2026-01-27 22:12:51'),
(152, 130, 'Nkandakulyowa', 'NKK', '2026-01-27 22:12:51'),
(153, 131, 'Buwaigala', 'BWG', '2026-01-27 22:12:51'),
(154, 131, 'Kiwalazi', 'KWL', '2026-01-27 22:12:51'),
(155, 131, 'Kizigo', 'KZG', '2026-01-27 22:12:51'),
(156, 131, 'Nakabaale B', 'NKB-B', '2026-01-27 22:12:51'),
(157, 131, 'Nakasedhere', 'NKS', '2026-01-27 22:12:51'),
(158, 132, 'Bubiro', 'BBR', '2026-01-27 22:12:51'),
(159, 132, 'Bugaga A', 'BGA-A', '2026-01-27 22:12:51'),
(160, 132, 'Bugaga B', 'BGA-B', '2026-01-27 22:12:51'),
(161, 132, 'Bugobi', 'BGB', '2026-01-27 22:12:51'),
(162, 132, 'Butogonya', 'BTG', '2026-01-27 22:12:51'),
(163, 132, 'Buyemba', 'BYM', '2026-01-27 22:12:51'),
(164, 132, 'Luzinga Park', 'LZP', '2026-01-27 22:12:51'),
(165, 132, 'Nawampiti', 'NWP', '2026-01-27 22:12:51'),
(166, 133, 'Buniko A', 'BNK-A', '2026-01-27 22:12:51'),
(167, 133, 'Buniko B', 'BNK-B', '2026-01-27 22:12:51'),
(168, 133, 'Mawale', 'MWL', '2026-01-27 22:12:51'),
(169, 133, 'Mboga', 'MBG', '2026-01-27 22:12:51'),
(170, 134, 'Kasokoso', 'KSK', '2026-01-27 22:12:51'),
(171, 134, 'Kibuye LC1', 'KBY', '2026-01-27 22:12:51'),
(172, 134, 'Kyanvuma Trading Center', 'KYT', '2026-01-27 22:12:51'),
(173, 134, 'Old Market', 'OLD', '2026-01-27 22:12:51'),
(174, 135, 'Bondo', 'BND', '2026-01-27 22:12:51'),
(175, 135, 'Nakabaale A', 'NKB-A', '2026-01-27 22:12:51'),
(176, 135, 'Nakabaale scheme', 'NKB-S', '2026-01-27 22:12:51'),
(177, 136, 'Kigaito', 'KGT', '2026-01-27 22:12:51'),
(178, 136, 'Kyanvuma', 'KYV', '2026-01-27 22:12:51'),
(179, 136, 'Nabikamba', 'NBK', '2026-01-27 22:12:51'),
(180, 136, 'Nakabambwe', 'NKB', '2026-01-27 22:12:51'),
(181, 137, 'Budugu', 'BDG', '2026-01-27 22:12:51'),
(182, 137, 'Bulinda', 'BLD', '2026-01-27 22:12:51'),
(183, 137, 'Mpala', 'MPL', '2026-01-27 22:12:51'),
(184, 137, 'Nsiima Trading Centre', 'NSM', '2026-01-27 22:12:51'),
(185, 138, 'Bugomba', 'BGM', '2026-01-27 22:12:51'),
(186, 138, 'Buwanda', 'BWD', '2026-01-27 22:12:51'),
(187, 138, 'Nawandyo', 'NWD', '2026-01-27 22:12:51'),
(188, 139, 'Buyoola', 'BYL', '2026-01-27 22:12:51'),
(189, 139, 'Ikonia A', 'IKA-A', '2026-01-27 22:12:51'),
(190, 139, 'Ikonia Busige', 'IKB', '2026-01-27 22:12:51'),
(191, 139, 'Ikonia Central', 'IKC', '2026-01-27 22:12:51'),
(192, 139, 'Nakyere', 'NKY', '2026-01-27 22:12:51'),
(193, 140, 'Buwamwa', 'BWM', '2026-01-27 22:12:51'),
(194, 140, 'Nabikuyi', 'NBK', '2026-01-27 22:12:51'),
(195, 140, 'Nakiswiga A', 'NKS-A', '2026-01-27 22:12:51'),
(196, 140, 'Nakiswiga B', 'NKS-B', '2026-01-27 22:12:51'),
(197, 140, 'Namagera', 'NMG', '2026-01-27 22:12:51'),
(198, 140, 'Njababona', 'NJB', '2026-01-27 22:12:51'),
(199, 141, 'Buzimba', 'BZM', '2026-01-27 22:12:51'),
(200, 141, 'Kituuto A', 'KTT-A', '2026-01-27 22:12:51'),
(201, 141, 'Kituuto B', 'KTT-B', '2026-01-27 22:12:51'),
(202, 141, 'Nawampiti-Bukyangwa', 'NWB', '2026-01-27 22:12:51'),
(203, 142, 'Kasozi', 'KSZ', '2026-01-27 22:12:51'),
(204, 142, 'Nawankompe A', 'NWK-A', '2026-01-27 22:12:51'),
(205, 142, 'Nawankompe B', 'NWK-B', '2026-01-27 22:12:51'),
(206, 142, 'Walulagaba', 'WLG', '2026-01-27 22:12:51'),
(207, 143, 'Bulindi', 'BLD', '2026-01-27 22:12:51'),
(208, 143, 'Busiiro', 'BSR', '2026-01-27 22:12:51'),
(209, 143, 'Busiiro TC', 'BST', '2026-01-27 22:12:51'),
(210, 143, 'Bwamba', 'BWM', '2026-01-27 22:12:51'),
(211, 143, 'Kyamawundo', 'KYM', '2026-01-27 22:12:51'),
(212, 143, 'Nanvunano A', 'NVN-A', '2026-01-27 22:12:51'),
(213, 143, 'Nanvunano B', 'NVN-B', '2026-01-27 22:12:51'),
(214, 143, 'Nanvunano C', 'NVN-C', '2026-01-27 22:12:51'),
(215, 144, 'Bukyogo', 'BKY', '2026-01-27 22:12:51'),
(216, 144, 'Butimbwa A', 'BTM-A', '2026-01-27 22:12:51'),
(217, 144, 'Butimbwa B', 'BTM-B', '2026-01-27 22:12:51'),
(218, 144, 'Ikonko', 'IKK', '2026-01-27 22:12:51'),
(219, 144, 'Lwanika', 'LWN', '2026-01-27 22:12:51'),
(220, 144, 'Namakakale A', 'NMK-A', '2026-01-27 22:12:51'),
(221, 144, 'Namakakale B', 'NMK-B', '2026-01-27 22:12:51'),
(222, 144, 'Waibuga A', 'WBG-A', '2026-01-27 22:12:51'),
(223, 144, 'Waibuga B', 'WBG-B', '2026-01-27 22:12:51'),
(224, 145, 'Bukapala', 'BKP', '2026-01-27 22:12:51'),
(225, 145, 'Buwiiri', 'BWR', '2026-01-27 22:12:51'),
(226, 145, 'Itakaibolu A', 'ITK-A', '2026-01-27 22:12:51'),
(227, 145, 'Itakaibolu B', 'ITK-B', '2026-01-27 22:12:51'),
(228, 145, 'Kigaya', 'KGY', '2026-01-27 22:12:51'),
(229, 146, 'Kiwanyi', 'KWY', '2026-01-27 22:12:51'),
(230, 146, 'Lwaki', 'LWK', '2026-01-27 22:12:51'),
(231, 146, 'Maumo', 'MAM', '2026-01-27 22:12:51'),
(232, 146, 'Namadope', 'NMD', '2026-01-27 22:12:51'),
(233, 147, 'Bukooma B', 'BKM-B', '2026-01-27 22:12:51'),
(234, 147, 'Bukooma a', 'BKM-A', '2026-01-27 22:12:51'),
(235, 147, 'Misita', 'MST', '2026-01-27 22:12:51'),
(236, 148, 'Budhaana A', 'BDH-A', '2026-01-27 22:12:51'),
(237, 148, 'Budhaana B', 'BDH-B', '2026-01-27 22:12:51'),
(238, 148, 'Bukyangwa A', 'BKY-A', '2026-01-27 22:12:51'),
(239, 148, 'Bukyangwa B', 'BKY-B', '2026-01-27 22:12:51'),
(240, 149, 'Naigobya A', 'NGB-A', '2026-01-27 22:12:51'),
(241, 149, 'Naigobya B', 'NGB-B', '2026-01-27 22:12:51'),
(242, 149, 'Naigobya T/C', 'NGB-T', '2026-01-27 22:12:51'),
(243, 149, 'Nairika East', 'NRK-E', '2026-01-27 22:12:51'),
(244, 149, 'Nairika West', 'NRK-W', '2026-01-27 22:12:51'),
(245, 150, 'Bulalu', 'BLL', '2026-01-27 22:12:51'),
(246, 150, 'Busaku', 'BSK', '2026-01-27 22:12:51'),
(247, 150, 'Kirimwa A', 'KRM-A', '2026-01-27 22:12:51'),
(248, 150, 'Kirimwa B', 'KRM-B', '2026-01-27 22:12:51'),
(249, 150, 'Nabimogo A', 'NBM-A', '2026-01-27 22:12:51'),
(250, 150, 'Nabimogo B', 'NBM-B', '2026-01-27 22:12:51'),
(251, 150, 'Namansenda A', 'NMS-A', '2026-01-27 22:12:51'),
(252, 150, 'Namansenda B', 'NMS-B', '2026-01-27 22:12:51'),
(253, 151, 'Gwembuzi A', 'GWM-A', '2026-01-27 22:12:51'),
(254, 151, 'Gwembuzi B', 'GWM-B', '2026-01-27 22:12:51'),
(255, 151, 'Namulanda A', 'NML-A', '2026-01-27 22:12:51'),
(256, 151, 'Namulanda B', 'NML-B', '2026-01-27 22:12:51'),
(257, 152, 'Bumyuka', 'BMY', '2026-01-27 22:12:51'),
(258, 152, 'Buyego', 'BYG', '2026-01-27 22:12:51'),
(259, 152, 'Ibanda Yonna', 'IBY', '2026-01-27 22:12:51'),
(260, 152, 'Isaka Buga', 'ISB', '2026-01-27 22:12:51'),
(261, 152, 'Luganda', 'LGD', '2026-01-27 22:12:51'),
(262, 153, 'Agape Zone', 'AGP', '2026-01-27 22:12:51'),
(263, 153, 'Central Zone', 'CTZ', '2026-01-27 22:12:51'),
(264, 153, 'Kisambira Zone', 'KSM', '2026-01-27 22:12:51'),
(265, 153, 'Kunya Zone', 'KNY', '2026-01-27 22:12:51'),
(266, 153, 'Yonna Zone', 'YNN', '2026-01-27 22:12:51'),
(267, 154, 'Bufumba Zone', 'BFM', '2026-01-27 22:12:51'),
(268, 154, 'Bugumba Zone', 'BGM', '2026-01-27 22:12:51'),
(269, 154, 'Kilangila Zone', 'KLG', '2026-01-27 22:12:51'),
(270, 154, 'Kiteso Zone', 'KTS', '2026-01-27 22:12:51'),
(271, 155, 'Bugaya Zone', 'BGY', '2026-01-27 22:12:51'),
(272, 155, 'Bukoova PS Zone', 'BKP', '2026-01-27 22:12:51'),
(273, 155, 'Bususwa Zone', 'BSS', '2026-01-27 22:12:51'),
(274, 155, 'Busuuyi Zone', 'BSY', '2026-01-27 22:12:51'),
(275, 155, 'Buyingo Zone', 'BYG', '2026-01-27 22:12:51'),
(276, 156, 'Budoola Zone', 'BDL', '2026-01-27 22:12:51'),
(277, 156, 'Bwinike Zone', 'BWN', '2026-01-27 22:12:51'),
(278, 156, 'Central Zone', 'CTZ', '2026-01-27 22:12:51'),
(279, 156, 'Landi Zone', 'LND', '2026-01-27 22:12:51'),
(280, 156, 'Ngalambi Zone', 'NGL', '2026-01-27 22:12:51'),
(281, 157, 'Bufumba Zone', 'BFM', '2026-01-27 22:12:51'),
(282, 157, 'Bugaga Zone', 'BGA', '2026-01-27 22:12:51'),
(283, 157, 'Bulangira Zone', 'BLG', '2026-01-27 22:12:51'),
(284, 157, 'Central Zone', 'CTZ', '2026-01-27 22:12:51'),
(285, 158, 'Bufumba Zone', 'BFM', '2026-01-27 22:12:51'),
(286, 158, 'Bukyega Zone', 'BKY', '2026-01-27 22:12:51'),
(287, 158, 'Busuubo Zone', 'BSB', '2026-01-27 22:12:51'),
(288, 158, 'Buyingo Zone', 'BYG', '2026-01-27 22:12:51'),
(289, 158, 'Teso Zone', 'TSO', '2026-01-27 22:12:51'),
(290, 159, 'Bubiro Zone', 'BBR', '2026-01-27 22:12:51'),
(291, 159, 'Budhugu Zone', 'BDG', '2026-01-27 22:12:51'),
(292, 159, 'Buyingo Zone', 'BYG', '2026-01-27 22:12:51'),
(293, 159, 'Bwanda Zone', 'BWD', '2026-01-27 22:12:51'),
(294, 160, 'Bukama Zone', 'BKM', '2026-01-27 22:12:51'),
(295, 160, 'Central Zone', 'CTZ', '2026-01-27 22:12:51'),
(296, 160, 'Kisita Zone', 'KST', '2026-01-27 22:12:51'),
(297, 160, 'Mutyagoma Zone', 'MTG', '2026-01-27 22:12:51'),
(298, 160, 'Railway Zone', 'RWY', '2026-01-27 22:12:51'),
(299, 160, 'Wakasa Zone', 'WKS', '2026-01-27 22:12:51'),
(300, 161, 'Bukubembe/Buguru Zone', 'BKB', '2026-01-27 22:12:51'),
(301, 161, 'Bukwanga Zone', 'BKW', '2026-01-27 22:12:51'),
(302, 161, 'Bulondo Zone', 'BLD', '2026-01-27 22:12:51'),
(303, 161, 'Buyawuka Zone', 'BYW', '2026-01-27 22:12:51'),
(304, 161, 'Central Zone', 'CTZ', '2026-01-27 22:12:51'),
(305, 161, 'Kiseege Zone', 'KSG', '2026-01-27 22:12:51'),
(306, 161, 'Landi Zone', 'LND', '2026-01-27 22:12:51'),
(307, 11, 'BUGONO', 'BGN-1', '2026-01-27 22:12:51'),
(308, 11, 'NABINONYI', 'NBN', '2026-01-27 22:12:51'),
(309, 11, 'BUGONO B', 'BGN-B', '2026-01-27 22:12:51'),
(310, 12, 'BUVULE', 'BVL', '2026-01-27 22:12:51'),
(311, 12, 'ITANDA - BUWEIRA', 'ITB', '2026-01-27 22:12:51'),
(312, 12, 'KINU', 'KNU', '2026-01-27 22:12:51'),
(313, 12, 'BUKAIGO', 'BKG', '2026-01-27 22:12:51'),
(314, 13, 'BULIGANHA', 'BLG', '2026-01-27 22:12:51'),
(315, 13, 'ITUBA A', 'ITB-A', '2026-01-27 22:12:51'),
(316, 13, 'KABIRA A', 'KBR-A', '2026-01-27 22:12:51'),
(317, 13, 'ITUBA BUNIGULE', 'ITB-B', '2026-01-27 22:12:51'),
(318, 13, 'KABIRA B', 'KBR-B', '2026-01-27 22:12:51'),
(319, 13, 'BUIGANHA B', 'BIG-B', '2026-01-27 22:12:51'),
(320, 14, 'BUWEREMPE', 'BWR', '2026-01-27 22:12:51'),
(321, 14, 'KASAMBIKA I', 'KSM-1', '2026-01-27 22:12:51'),
(322, 14, 'KASAMBIKA II', 'KSM-2', '2026-01-27 22:12:51'),
(323, 14, 'NAMUSIISI I', 'NMS-1', '2026-01-27 22:12:51'),
(324, 14, 'NAMUSIISI II', 'NMS-2', '2026-01-27 22:12:51'),
(325, 15, 'BUBEKO', 'BBK', '2026-01-27 22:12:51'),
(326, 15, 'KALUNGAMI \'A\'', 'KLG-A', '2026-01-27 22:12:51'),
(327, 15, 'KALUNGAMI \'B\'', 'KLG-B', '2026-01-27 22:12:51'),
(328, 15, 'NABITENDE', 'NBT-1', '2026-01-27 22:12:51'),
(329, 15, 'BUTABALA', 'BTB', '2026-01-27 22:12:51'),
(330, 16, 'NALUKO', 'NLK-1', '2026-01-27 22:12:51'),
(331, 16, 'NAWANKWALE', 'NWK', '2026-01-27 22:12:51'),
(332, 16, 'NALUKO BUZIBIRILA', 'NLK-B', '2026-01-27 22:12:51'),
(333, 16, 'NAWANKWALE BUGWERE', 'NWK-B', '2026-01-27 22:12:51'),
(334, 17, 'KAMIRABIKOMO', 'KMR', '2026-01-27 22:12:51'),
(335, 17, 'MWIRA', 'MWR-1', '2026-01-27 22:12:51'),
(336, 17, 'NABITOVU', 'NBT-1', '2026-01-27 22:12:51'),
(337, 17, 'NABITOVU NORTH', 'NBT-N', '2026-01-27 22:12:51'),
(338, 18, 'NAMBALE I A', 'NMB-1A', '2026-01-27 22:12:51'),
(339, 18, 'NAMBALE I B', 'NMB-1B', '2026-01-27 22:12:51'),
(340, 18, 'NAMBALE II', 'NMB-2', '2026-01-27 22:12:51'),
(341, 19, 'BUSIMBA', 'BSM', '2026-01-27 22:12:51'),
(342, 19, 'NABUKONE', 'NBK', '2026-01-27 22:12:51'),
(343, 19, 'NASUUTI NORTH', 'NST-N', '2026-01-27 22:12:51'),
(344, 19, 'NASUUTI SOUTH', 'NST-S', '2026-01-27 22:12:51'),
(345, 19, 'KAKIRA', 'KKR', '2026-01-27 22:12:51'),
(346, 20, 'BUBOGO A', 'BBG-A', '2026-01-27 22:12:51'),
(347, 20, 'NABIKOOTE', 'NBK', '2026-01-27 22:12:51'),
(348, 20, 'NAMUFUMA', 'NMF', '2026-01-27 22:12:51'),
(349, 20, 'NAMUNKESU', 'NMK', '2026-01-27 22:12:51'),
(350, 20, 'BUBOGO B', 'BBG-B', '2026-01-27 22:12:51'),
(351, 21, 'BUFUTULA A', 'BFT-A', '2026-01-27 22:12:51'),
(352, 21, 'NAMUNSAALA', 'NMS', '2026-01-27 22:12:51'),
(353, 21, 'BUFUTULA B', 'BFT-B', '2026-01-27 22:12:51'),
(354, 22, 'NAWANSEGA A', 'NWS-A', '2026-01-27 22:12:51'),
(355, 22, 'NAWANSEGA B', 'NWS-B', '2026-01-27 22:12:51'),
(356, 23, 'BULUMWAKI I', 'BLM-1', '2026-01-27 22:12:51'),
(357, 23, 'BULUMWAKI II', 'BLM-2', '2026-01-27 22:12:51'),
(358, 23, 'NSINZE', 'NSZ', '2026-01-27 22:12:51'),
(359, 24, 'BULANGA', 'BLG', '2026-01-27 22:12:51'),
(360, 24, 'MWENDANFUKO', 'MWF', '2026-01-27 22:12:51'),
(361, 25, 'KAWETE', 'KWT', '2026-01-27 22:12:51'),
(362, 25, 'NAMUNGALWE RURAL', 'NMG-R', '2026-01-27 22:12:51'),
(363, 25, 'NAMUNGALWE A', 'NMG-A', '2026-01-27 22:12:51'),
(364, 25, 'NAMUNGALWE B', 'NMG-B', '2026-01-27 22:12:51'),
(365, 26, 'NAMUNKANAGA I', 'NMK-1', '2026-01-27 22:12:51'),
(366, 26, 'NAMUNKANAGA II', 'NMK-2', '2026-01-27 22:12:51'),
(367, 27, 'BUGOLE A', 'BGL-A', '2026-01-27 22:12:51'),
(368, 27, 'BUGOLE B', 'BGL-B', '2026-01-27 22:12:51'),
(369, 27, 'BUGONGO', 'BGG-1', '2026-01-27 22:12:51'),
(370, 27, 'NAMABWERE I', 'NMB-1', '2026-01-27 22:12:51'),
(371, 27, 'NAMABWERE II', 'NMB-2', '2026-01-27 22:12:51'),
(372, 27, 'NAMUKUMYA', 'NMK', '2026-01-27 22:12:51'),
(373, 27, 'NAWANDALA', 'NWD', '2026-01-27 22:12:51'),
(374, 27, 'NAWANGAIZA II', 'NWG-2', '2026-01-27 22:12:51'),
(375, 27, 'BUSAKAIRE', 'BSK', '2026-01-27 22:12:51'),
(376, 27, 'BUGONGO B', 'BGG-B', '2026-01-27 22:12:51'),
(377, 30, 'KIWANYI I', 'KWY-1', '2026-01-27 22:12:51'),
(378, 30, 'KIWANYI II', 'KWY-2', '2026-01-27 22:12:51'),
(379, 30, 'BUSAALA', 'BSL', '2026-01-27 22:12:51'),
(380, 30, 'BUWUMBA', 'BWM', '2026-01-27 22:12:51'),
(381, 30, 'MADHIMASU', 'MDH', '2026-01-27 22:12:51'),
(382, 30, 'BUKYEEGA', 'BKY', '2026-01-27 22:12:51'),
(383, 29, 'BUGAMBO', 'BGM', '2026-01-27 22:12:51'),
(384, 29, 'BUNYOKANO', 'BNY', '2026-01-27 22:12:51'),
(385, 29, 'BUSOIGI', 'BSG', '2026-01-27 22:12:51'),
(386, 29, 'BUZAAYA', 'BZY', '2026-01-27 22:12:51'),
(387, 29, 'IKUMBYA', 'IKM', '2026-01-27 22:12:51'),
(388, 29, 'KABULI I', 'KBL-1', '2026-01-27 22:12:51'),
(389, 29, 'KABULI II', 'KBL-2', '2026-01-27 22:12:51'),
(390, 29, 'KYENDABAWALA', 'KYB', '2026-01-27 22:12:51'),
(391, 28, 'BUYUNGA', 'BYG', '2026-01-27 22:12:51'),
(392, 28, 'MALOBI', 'MLB', '2026-01-27 22:12:51'),
(393, 28, 'NAMUSIISI', 'NMS-1', '2026-01-27 22:12:51'),
(394, 28, 'BUGANZA', 'BGZ', '2026-01-27 22:12:51'),
(395, 31, 'KIRINGA A', 'KRG-A', '2026-01-27 22:12:51'),
(396, 31, 'KIRINGA B', 'KRG-B', '2026-01-27 22:12:51'),
(397, 31, 'NAWANGAIZA I', 'NWG-1', '2026-01-27 22:12:51'),
(398, 32, 'NAIBIRI CENTRAL', 'NBR-C', '2026-01-27 22:12:51'),
(399, 32, 'NAIBIRI NORTH', 'NBR-N', '2026-01-27 22:12:51'),
(400, 32, 'NAIBIRI SOUTH', 'NBR-S', '2026-01-27 22:12:51'),
(401, 33, 'KIDAAGO A', 'KDG-A', '2026-01-27 22:12:51'),
(402, 33, 'KIDAAGO B', 'KDG-B', '2026-01-27 22:12:51'),
(403, 34, 'KAZIGO A', 'KZG-A', '2026-01-27 22:12:51'),
(404, 34, 'KAZIGO B', 'KZG-B', '2026-01-27 22:12:51'),
(405, 35, 'NABITENDE A', 'NBT-A', '2026-01-27 22:12:51'),
(406, 35, 'NABITENDE B', 'NBT-B', '2026-01-27 22:12:51'),
(407, 35, 'BUSABI ZONE', 'BSB', '2026-01-27 22:12:51'),
(408, 35, 'BUKOSE ZONE', 'BKS', '2026-01-27 22:12:51'),
(409, 35, 'BUYALE ZONE', 'BYL', '2026-01-27 22:12:51'),
(410, 36, 'BUDHWEGE', 'BDW', '2026-01-27 22:12:51'),
(411, 36, 'BUKOYO', 'BKY-1', '2026-01-27 22:12:51'),
(412, 36, 'NAWANSINGE', 'NWS', '2026-01-27 22:12:51'),
(413, 36, 'BUKABISI', 'BKB', '2026-01-27 22:12:51'),
(414, 37, 'BUBAKA', 'BBK', '2026-01-27 22:12:51'),
(415, 37, 'BULAMAGI', 'BLG-1', '2026-01-27 22:12:51'),
(416, 38, 'KASOLO', 'KSL', '2026-01-27 22:12:51'),
(417, 38, 'BULOWOOZA', 'BLW-1', '2026-01-27 22:12:51'),
(418, 38, 'MADHIGANDERE', 'MDG', '2026-01-27 22:12:51'),
(419, 38, 'NGANGALI', 'NGL', '2026-01-27 22:12:51'),
(420, 38, 'WALUKUBA', 'WLK', '2026-01-27 22:12:51'),
(421, 38, 'MAWOITO', 'MWT-1', '2026-01-27 22:12:51'),
(422, 39, 'BUDHEBERA', 'BDB', '2026-01-27 22:12:51'),
(423, 39, 'IGULAMUBIRI', 'IGL', '2026-01-27 22:12:51'),
(424, 39, 'BUWASA', 'BWS', '2026-01-27 22:12:51'),
(425, 39, 'BUYUBU', 'BYB', '2026-01-27 22:12:51'),
(426, 39, 'BWANALIRA', 'BWN-1', '2026-01-27 22:12:51'),
(427, 39, 'KINAWANSWA', 'KNW', '2026-01-27 22:12:51'),
(428, 40, 'BUWOYA', 'BWY', '2026-01-27 22:12:51'),
(429, 40, 'IWAWU', 'IWW-1', '2026-01-27 22:12:51'),
(430, 40, 'KYEMEIRE', 'KYM', '2026-01-27 22:12:52'),
(431, 40, 'MASABA', 'MSB', '2026-01-27 22:12:52'),
(432, 40, 'NAMASOGA', 'NMS', '2026-01-27 22:12:52'),
(433, 40, 'NAWANKOFU', 'NWK', '2026-01-27 22:12:52'),
(434, 40, 'NKAZIWERU', 'NKZ', '2026-01-27 22:12:52'),
(435, 40, 'NTINDA', 'NTD', '2026-01-27 22:12:52'),
(436, 40, 'NAMALEMBA', 'NML', '2026-01-27 22:12:52'),
(437, 41, 'BUKAYE', 'BKY-1', '2026-01-27 22:12:52'),
(438, 41, 'BUWONGO', 'BWG', '2026-01-27 22:12:52'),
(439, 41, 'NAMPIRIKA A', 'NMP-A', '2026-01-27 22:12:52'),
(440, 41, 'NAMPIRIKA B', 'NMP-B', '2026-01-27 22:12:52'),
(441, 41, 'IGULUSA', 'IGL', '2026-01-27 22:12:52'),
(442, 42, 'BUPALA', 'BPL', '2026-01-27 22:12:52'),
(443, 42, 'KAKONGOKA', 'KKG-1', '2026-01-27 22:12:52'),
(444, 42, 'NAMUNDUDI A', 'NMD-A', '2026-01-27 22:12:52'),
(445, 42, 'NAMUNDUDI B', 'NMD-B', '2026-01-27 22:12:52'),
(446, 42, 'KAKONGOKA B', 'KKG-B', '2026-01-27 22:12:52'),
(447, 42, 'NAMUNDUDI C', 'NMD-C', '2026-01-27 22:12:52'),
(448, 42, 'BUKALAMBWA', 'BKL', '2026-01-27 22:12:52'),
(449, 43, 'BUSEYI A', 'BSY-A', '2026-01-27 22:12:52'),
(450, 43, 'BUSEYI B', 'BSY-B', '2026-01-27 22:12:52'),
(451, 43, 'BUSEYI CENTRAL', 'BSY-C', '2026-01-27 22:12:52'),
(452, 44, 'BUKOBOOLI', 'BKB', '2026-01-27 22:12:52'),
(453, 44, 'BUKYAYE', 'BKY', '2026-01-27 22:12:52'),
(454, 44, 'BUTAAMA', 'BTM', '2026-01-27 22:12:52'),
(455, 44, 'NABIRYE', 'NBR', '2026-01-27 22:12:52'),
(456, 44, 'NAKALAMA CENTRAL', 'NKL-C', '2026-01-27 22:12:52'),
(457, 44, 'NAKALAMA SOUTH', 'NKL-S', '2026-01-27 22:12:52'),
(458, 44, 'NAKALAMA NORTH', 'NKL-N', '2026-01-27 22:12:52'),
(459, 45, 'BUGABWE', 'BGB', '2026-01-27 22:12:52'),
(460, 45, 'BULUBANDI CENTRAL A', 'BLB-A', '2026-01-27 22:12:52'),
(461, 45, 'NANDEKULA A', 'NND-A', '2026-01-27 22:12:52'),
(462, 45, 'BULUBANDI CENTRAL B', 'BLB-B', '2026-01-27 22:12:52'),
(463, 45, 'NANDEKULA B', 'NND-B', '2026-01-27 22:12:52'),
(464, 46, 'BUKWAYA', 'BKW', '2026-01-27 22:12:52'),
(465, 46, 'BUNYAMA', 'BNY-1', '2026-01-27 22:12:52'),
(466, 46, 'KIBOYO', 'KBY', '2026-01-27 22:12:52'),
(467, 46, 'NAMIRALI', 'NMR', '2026-01-27 22:12:52'),
(468, 47, 'BUSOWOOBI- NYENGA', 'BSW-N', '2026-01-27 22:12:52'),
(469, 47, 'BUSOWOOBI CENTRAL', 'BSW-C', '2026-01-27 22:12:52'),
(470, 47, 'NABITOVU', 'NBT', '2026-01-27 22:12:52'),
(471, 47, 'NAKIGO I', 'NKG-1', '2026-01-27 22:12:52'),
(472, 47, 'NAKIGO II', 'NKG-2', '2026-01-27 22:12:52'),
(473, 47, 'KIWERERE', 'KWR', '2026-01-27 22:12:52'),
(474, 48, 'BULUZA', 'BLZ', '2026-01-27 22:12:52'),
(475, 48, 'KABIRA', 'KBR-1', '2026-01-27 22:12:52'),
(476, 48, 'NAWANZU', 'NWZ', '2026-01-27 22:12:52'),
(477, 48, 'NAMUSENWA', 'NMS', '2026-01-27 22:12:52'),
(478, 49, 'IZIMBA', 'IZM', '2026-01-27 22:12:52'),
(479, 49, 'KAKOMBO', 'KKM', '2026-01-27 22:12:52'),
(480, 49, 'NAKISENYI', 'NKS', '2026-01-27 22:12:52'),
(481, 49, 'WAIRAMA', 'WRM-1', '2026-01-27 22:12:52'),
(482, 50, 'BUNYIIRO', 'BNY-1', '2026-01-27 22:12:52'),
(483, 50, 'BUWOLOMERA A', 'BWL-A', '2026-01-27 22:12:52'),
(484, 50, 'BUWOLOMER B', 'BWL-B', '2026-01-27 22:12:52'),
(485, 50, 'NAGADUDULA', 'NGD', '2026-01-27 22:12:52'),
(486, 50, 'BUKOSE', 'BKS', '2026-01-27 22:12:52'),
(487, 50, 'LWABAGA', 'LWB', '2026-01-27 22:12:52'),
(488, 51, 'BUKONKO', 'BKK', '2026-01-27 22:12:52'),
(489, 51, 'LWERERA', 'LWR', '2026-01-27 22:12:52'),
(490, 51, 'MAGOGO', 'MGG-1', '2026-01-27 22:12:52'),
(491, 51, 'NAKIRULWE', 'NKR', '2026-01-27 22:12:52'),
(492, 51, 'NAWANDYO', 'NWD', '2026-01-27 22:12:52'),
(493, 51, 'BUWANDE', 'BWD', '2026-01-27 22:12:52'),
(494, 51, 'BUWENDA', 'BWN', '2026-01-27 22:12:52'),
(495, 52, 'MAWAGALA', 'MWG', '2026-01-27 22:12:52'),
(496, 52, 'NAWANKONGE', 'NWK', '2026-01-27 22:12:52'),
(497, 52, 'NAWANYINGI', 'NWY-1', '2026-01-27 22:12:52'),
(498, 52, 'MBAALA', 'MBL', '2026-01-27 22:12:52'),
(499, 52, 'BUWOIREKU', 'BWR', '2026-01-27 22:12:52'),
(500, 52, 'LUGOBANGO', 'LGB', '2026-01-27 22:12:52'),
(501, 52, 'WALUGOMA', 'WLG', '2026-01-27 22:12:52'),
(502, 53, 'LUBAALE', 'LBL', '2026-01-27 22:12:52'),
(503, 53, 'NAKAVULE \'A\'', 'NKV-A', '2026-01-27 22:12:52'),
(504, 53, 'NAKAVULE \'B\'', 'NKV-B', '2026-01-27 22:12:52'),
(505, 53, 'NAKAVULE MAIN', 'NKV-M', '2026-01-27 22:12:52'),
(506, 54, 'BULIGO SOUTH A', 'BLG-A', '2026-01-27 22:12:52'),
(507, 54, 'BULIGO SOUTH', 'BLG-S', '2026-01-27 22:12:52'),
(508, 54, 'NABIDONGA C', 'NBD-C', '2026-01-27 22:12:52'),
(509, 54, 'NABIDONGHA PRISONS', 'NBD-P', '2026-01-27 22:12:52'),
(510, 55, 'NABIDONGHA A', 'NBD-A', '2026-01-27 22:12:52'),
(511, 55, 'NABIDONGHA B', 'NBD-B', '2026-01-27 22:12:52'),
(512, 55, 'NABIDONGHA PROPER', 'NBD-PR', '2026-01-27 22:12:52'),
(513, 56, 'KASOKOSO CENTRAL III', 'KSK-3', '2026-01-27 22:12:52'),
(514, 56, 'WALUGOGO HOUSING ESTATE', 'WLG-H', '2026-01-27 22:12:52'),
(515, 57, 'KASOKOSO CENTRAL I', 'KSK-1', '2026-01-27 22:12:52'),
(516, 57, 'KASOKOSO CENTRAL II', 'KSK-2', '2026-01-27 22:12:52'),
(517, 58, 'BULIGO NORTH', 'BLG-N', '2026-01-27 22:12:52'),
(518, 58, 'KASOKOSO NORTH', 'KSK-N', '2026-01-27 22:12:52'),
(519, 58, 'KASOKOSO SOUTH', 'KSK-S', '2026-01-27 22:12:52'),
(520, 58, 'KAYAGA', 'KYG', '2026-01-27 22:12:52'),
(521, 59, 'NKONO II', 'NKN-2', '2026-01-27 22:12:52'),
(522, 59, 'NKONO CENTRAL', 'NKN-C', '2026-01-27 22:12:52'),
(523, 59, 'SILIVE', 'SLV', '2026-01-27 22:12:52'),
(524, 60, 'BIKADHO', 'BKD', '2026-01-27 22:12:52'),
(525, 60, 'IGAMBA', 'IGB', '2026-01-27 22:12:52'),
(526, 60, 'IGAMBA SOUTH', 'IGB-S', '2026-01-27 22:12:52'),
(527, 61, 'MUTAMBALA', 'MTM', '2026-01-27 22:12:52'),
(528, 61, 'MUTUKULA', 'MTK', '2026-01-27 22:12:52'),
(529, 61, 'NKONO I', 'NKN-1', '2026-01-27 22:12:52'),
(530, 61, 'NKONO III', 'NKN-3', '2026-01-27 22:12:52'),
(531, 62, 'KILOWA', 'KLW', '2026-01-27 22:12:52'),
(532, 62, 'NKAATU MAIN', 'NKT-M', '2026-01-27 22:12:52'),
(533, 62, 'NKAATU PROPER', 'NKT-P', '2026-01-27 22:12:52'),
(534, 63, 'BUGUMBA A', 'BGM-A', '2026-01-27 22:12:52'),
(535, 63, 'BUGUMBA B', 'BGM-B', '2026-01-27 22:12:52'),
(536, 63, 'BUGUMBA CENTRAL', 'BGM-C', '2026-01-27 22:12:52'),
(537, 63, 'BUGUMBA UPPER', 'BGM-U', '2026-01-27 22:12:52'),
(538, 64, 'BULAKABYA', 'BLK', '2026-01-27 22:12:52'),
(539, 64, 'BUGAYA', 'BGY', '2026-01-27 22:12:52'),
(540, 64, 'BUGOBYA', 'BGB', '2026-01-27 22:12:52'),
(541, 64, 'BULONDO', 'BLD', '2026-01-27 22:12:52'),
(542, 64, 'LUKONKO', 'LKK', '2026-01-27 22:12:52'),
(543, 64, 'NABIRAMA', 'NBR', '2026-01-27 22:12:52'),
(544, 64, 'NAKATI', 'NKT', '2026-01-27 22:12:52'),
(545, 64, 'NAMAZALA', 'NMZ', '2026-01-27 22:12:52'),
(546, 64, 'NANFUGAKI', 'NNF', '2026-01-27 22:12:52'),
(547, 64, 'NYENGA', 'NYG', '2026-01-27 22:12:52'),
(548, 65, 'BUGONGOLO', 'BGG', '2026-01-27 22:12:52'),
(549, 65, 'ITAKAIBOLU', 'ITK', '2026-01-27 22:12:52'),
(550, 65, 'KALIRO/BUPUPA', 'KLR', '2026-01-27 22:12:52'),
(551, 65, 'KASITA', 'KST', '2026-01-27 22:12:52'),
(552, 65, 'KASOZI', 'KSZ', '2026-01-27 22:12:52'),
(553, 65, 'KIGALAGALA', 'KGL', '2026-01-27 22:12:52'),
(554, 65, 'MPAMBWE', 'MPM', '2026-01-27 22:12:52'),
(555, 65, 'NAMATOLO', 'NMT', '2026-01-27 22:12:52'),
(556, 65, 'WALUMBUGU', 'WLM', '2026-01-27 22:12:52'),
(557, 66, 'BULINDA', 'BLD', '2026-01-27 22:12:52'),
(558, 66, 'IRERA', 'IRR', '2026-01-27 22:12:52'),
(559, 66, 'KAKUBA', 'KKB', '2026-01-27 22:12:52'),
(560, 66, 'KATALAKABI', 'KTL', '2026-01-27 22:12:52'),
(561, 66, 'KISASI', 'KSS', '2026-01-27 22:12:52'),
(562, 66, 'NABULAGALA', 'NBL', '2026-01-27 22:12:52'),
(563, 66, 'NAKABALE', 'NKB', '2026-01-27 22:12:52'),
(564, 66, 'NAMAGANGA', 'NMG', '2026-01-27 22:12:52'),
(565, 66, 'NAMAZINGIRI', 'NMZ', '2026-01-27 22:12:52'),
(566, 66, 'NKALANGE', 'NKL', '2026-01-27 22:12:52'),
(567, 67, 'BUSIGE', 'BSG', '2026-01-27 22:12:52'),
(568, 67, 'BUWOLOMERA', 'BWL', '2026-01-27 22:12:52'),
(569, 67, 'BWIDHABWANGU', 'BWD', '2026-01-27 22:12:52'),
(570, 67, 'IRONGO', 'IRG', '2026-01-27 22:12:52'),
(571, 67, 'ITENGEZA', 'ITG', '2026-01-27 22:12:52'),
(572, 67, 'KISIRIRA', 'KSR', '2026-01-27 22:12:52'),
(573, 67, 'NABITAMBALA', 'NBT', '2026-01-27 22:12:52'),
(574, 67, 'NABIWAWULO', 'NBW', '2026-01-27 22:12:52'),
(575, 67, 'WANTUNDA', 'WNT', '2026-01-27 22:12:52'),
(576, 68, 'BUDHOOMA', 'BDH', '2026-01-27 22:12:52'),
(577, 68, 'KANAMA', 'KNM', '2026-01-27 22:12:52'),
(578, 68, 'KIKO', 'KKO', '2026-01-27 22:12:52'),
(579, 68, 'KINABIRYE', 'KNB', '2026-01-27 22:12:52'),
(580, 68, 'LWINO', 'LWN', '2026-01-27 22:12:52'),
(581, 68, 'NALINAIBI', 'NLN', '2026-01-27 22:12:52'),
(582, 68, 'NTINDA', 'NTD', '2026-01-27 22:12:52'),
(583, 69, '1.10', '110', '2026-01-27 22:12:52'),
(584, 69, 'BANGALOW', 'BGL', '2026-01-27 22:12:52'),
(585, 69, 'GO MOJA', 'GMJ', '2026-01-27 22:12:52'),
(586, 69, 'LINE 40', 'L40', '2026-01-27 22:12:52'),
(587, 69, 'MAJIMAZULI', 'MJM', '2026-01-27 22:12:52'),
(588, 69, 'NTINKALU', 'NTK', '2026-01-27 22:12:52'),
(589, 69, 'NYANZA QUARTER', 'NYQ', '2026-01-27 22:12:52'),
(590, 69, 'SINGLE QUARTER', 'SQR', '2026-01-27 22:12:52'),
(591, 70, 'LAND/KATOOKE', 'LKT', '2026-01-27 22:12:52'),
(592, 70, 'KIRINYA', 'KRY', '2026-01-27 22:12:52'),
(593, 70, 'KOROKOTO', 'KRK', '2026-01-27 22:12:52'),
(594, 70, 'KHAT/KASABA', 'KHT', '2026-01-27 22:12:52'),
(595, 70, 'MUTAI', 'MTI', '2026-01-27 22:12:52'),
(596, 70, 'Q.6', 'Q06', '2026-01-27 22:12:52'),
(597, 70, 'TEREGO', 'TRG', '2026-01-27 22:12:52'),
(598, 70, 'WELFARE/STAFF QUARTERS', 'WFR', '2026-01-27 22:12:52'),
(599, 71, 'KABEMBE A', 'KBM-A', '2026-01-27 22:12:52'),
(600, 71, 'KABEMBE B', 'KBM-B', '2026-01-27 22:12:52'),
(601, 71, 'KAGOGWA', 'KGG', '2026-01-27 22:12:52'),
(602, 71, 'MAWOITO A', 'MWT-A', '2026-01-27 22:12:52'),
(603, 71, 'MAWOITO B', 'MWT-B', '2026-01-27 22:12:52'),
(604, 72, 'NALUBAALE', 'NLB', '2026-01-27 22:12:52'),
(605, 72, 'WAIRAKA A', 'WRK-A', '2026-01-27 22:12:52'),
(606, 72, 'WAIRAKA CENTRAL', 'WRK-C', '2026-01-27 22:12:52'),
(607, 72, 'WAIRAKA COLLEGE', 'WRK-CG', '2026-01-27 22:12:52'),
(608, 72, 'WALUMBE', 'WLM', '2026-01-27 22:12:52'),
(609, 73, 'BATI SAFI', 'BTS', '2026-01-27 22:12:52'),
(610, 73, 'KAGOMA GATE', 'KGG', '2026-01-27 22:12:52'),
(611, 73, 'KALANTIN', 'KLN', '2026-01-27 22:12:52'),
(612, 73, 'KYENDA', 'KYD', '2026-01-27 22:12:52'),
(613, 73, 'MATAFALI', 'MTF', '2026-01-27 22:12:52'),
(614, 74, 'F.F.1', 'FF1', '2026-01-27 22:12:52'),
(615, 74, 'G.G.3', 'GG3', '2026-01-27 22:12:52'),
(616, 74, 'KABYAZA', 'KBZ', '2026-01-27 22:12:52'),
(617, 74, 'LINE KUBWA', 'LKB', '2026-01-27 22:12:52'),
(618, 74, 'LINE MABATI', 'LMB', '2026-01-27 22:12:52'),
(619, 74, 'LINE RAILWAY', 'LRW', '2026-01-27 22:12:52'),
(620, 74, 'LINE SAMIA', 'LSM', '2026-01-27 22:12:52'),
(621, 74, 'LINE SECURITY', 'LSC', '2026-01-27 22:12:52'),
(622, 74, 'LINYA', 'LNY', '2026-01-27 22:12:52'),
(623, 75, 'BUSOGA COLLEGE MWIRI', 'BCM', '2026-01-27 22:12:52'),
(624, 75, 'KINYORO-KITESO', 'KKT', '2026-01-27 22:12:52'),
(625, 75, 'MWIRI PRIMARY SCHOOL', 'MPS', '2026-01-27 22:12:52'),
(626, 75, 'NAKIGO', 'NKG', '2026-01-27 22:12:52'),
(627, 75, 'NAMAZIBA', 'NMZ', '2026-01-27 22:12:52'),
(628, 75, 'WAIRAKA B', 'WRK-B', '2026-01-27 22:12:52'),
(629, 76, 'DUMBA', 'DMB', '2026-01-27 22:12:52'),
(630, 76, 'NALONGO', 'NLG', '2026-01-27 22:12:52'),
(631, 76, 'POLOTA B', 'PLT-B', '2026-01-27 22:12:52'),
(632, 76, 'MARKET', 'MKT', '2026-01-27 22:12:52'),
(633, 76, 'POLOTA A', 'PLT-A', '2026-01-27 22:12:52'),
(634, 76, 'SCHOOL', 'SCH', '2026-01-27 22:12:52'),
(635, 77, 'BUDIMA', 'BDM', '2026-01-27 22:12:52'),
(636, 77, 'BITULI', 'BTL', '2026-01-27 22:12:52'),
(637, 77, 'BUWUMA EAST', 'BWM-E', '2026-01-27 22:12:52'),
(638, 77, 'BUWUMA WEST A', 'BWM-WA', '2026-01-27 22:12:52'),
(639, 77, 'BUWUMA WEST B', 'BWM-WB', '2026-01-27 22:12:52'),
(640, 77, 'KABEMBE EAST', 'KBM-E', '2026-01-27 22:12:52'),
(641, 77, 'KABEMBE WEST', 'KBM-W', '2026-01-27 22:12:52'),
(642, 77, 'KIWAGAMA NORTH', 'KWG-N', '2026-01-27 22:12:52'),
(643, 77, 'KIWAGAMA SOUTH', 'KWG-S', '2026-01-27 22:12:52'),
(644, 77, 'NAKASEGETE', 'NKS', '2026-01-27 22:12:52'),
(645, 78, 'BUWALA A', 'BWL-A', '2026-01-27 22:12:52'),
(646, 78, 'BUWALA B', 'BWL-B', '2026-01-27 22:12:52'),
(647, 78, 'BUWALA C (ITANDA)', 'BWL-C', '2026-01-27 22:12:52'),
(648, 78, 'IWOLOLO B', 'IWL-B', '2026-01-27 22:12:52'),
(649, 78, 'IWOLOLO A', 'IWL-A', '2026-01-27 22:12:52'),
(650, 78, 'KISOZI A', 'KSZ-A', '2026-01-27 22:12:52'),
(651, 78, 'KISOZI B', 'KSZ-B', '2026-01-27 22:12:52'),
(652, 78, 'LUMULI KALUGU D', 'LML-D', '2026-01-27 22:12:52'),
(653, 78, 'LUMULI B', 'LML-B', '2026-01-27 22:12:52'),
(654, 78, 'LUMULI A', 'LML-A', '2026-01-27 22:12:52'),
(655, 78, 'LUMULI C', 'LML-C', '2026-01-27 22:12:52'),
(656, 78, 'NAKAKULWE A', 'NKK-A', '2026-01-27 22:12:52'),
(657, 78, 'NAKAKULWE B', 'NKK-B', '2026-01-27 22:12:52'),
(658, 79, 'BUBUGO BUGOBI', 'BBG-BG', '2026-01-27 22:12:52'),
(659, 79, 'BUBUGO BULONDO', 'BBG-BL', '2026-01-27 22:12:52'),
(660, 79, 'BUBUGO CENTRAL', 'BBG-C', '2026-01-27 22:12:52'),
(661, 79, 'BWEIGAMYE', 'BWG', '2026-01-27 22:12:52'),
(662, 79, 'BUSOWOOKO B', 'BSW-B', '2026-01-27 22:12:52'),
(663, 79, 'BUSOWOOKO CENTRAL', 'BSW-C', '2026-01-27 22:12:52'),
(664, 79, 'NABUKOSI BUGAISO A', 'NBK-A', '2026-01-27 22:12:52'),
(665, 79, 'NABUKOSI BUGAISO B', 'NBK-B', '2026-01-27 22:12:52'),
(666, 79, 'NABUKOSI CENTRAL', 'NBK-C', '2026-01-27 22:12:52'),
(667, 79, 'BULONDO A', 'BLD-A', '2026-01-27 22:12:52'),
(668, 79, 'BULONDO B', 'BLD-B', '2026-01-27 22:12:52'),
(669, 79, 'BUWOLOMERA', 'BWL', '2026-01-27 22:12:52'),
(670, 79, 'NAWAMPANDA CENTRAL', 'NWP-C', '2026-01-27 22:12:52'),
(671, 80, 'BUTAGAYA WAIBUGA', 'BTG-W', '2026-01-27 22:12:52'),
(672, 80, 'BUTAGAYA BWASE', 'BTG-B', '2026-01-27 22:12:52'),
(673, 80, 'KIRANGA BUFUTA', 'KRG-BF', '2026-01-27 22:12:52'),
(674, 80, 'KIRANGA BUSOOBA', 'KRG-BS', '2026-01-27 22:12:52'),
(675, 80, 'KIRANGA BUSUSWA A', 'KRG-A', '2026-01-27 22:12:52'),
(676, 80, 'KIRANGA BUSUSWA B', 'KRG-B', '2026-01-27 22:12:52'),
(677, 80, 'KITENGESA BUGERERE', 'KTG-BG', '2026-01-27 22:12:52'),
(678, 80, 'KITENGESA MPEMUKIRABUSA', 'KTG-MP', '2026-01-27 22:12:52'),
(679, 80, 'WANSIMBA NAKABBALE', 'WNS-NK', '2026-01-27 22:12:52'),
(680, 80, 'WANSIMBA NAMAVUNDU', 'WNS-NM', '2026-01-27 22:12:52'),
(681, 81, 'KAMIRA', 'KMR', '2026-01-27 22:12:52'),
(682, 81, 'LUBIRA', 'LBR', '2026-01-27 22:12:52'),
(683, 81, 'MABIRA', 'MBR', '2026-01-27 22:12:52'),
(684, 81, 'BUGUMIRA A', 'BGM-A', '2026-01-27 22:12:52'),
(685, 81, 'BUGUMIRA B', 'BGM-B', '2026-01-27 22:12:52'),
(686, 81, 'NAMAGERA CENTRAL', 'NMG-C', '2026-01-27 22:12:52'),
(687, 82, 'KIBUNDAIRE BUDHAGA', 'KBD-BG', '2026-01-27 22:12:52'),
(688, 82, 'KIBUNDAIRE BUKWANGA', 'KBD-BK', '2026-01-27 22:12:52'),
(689, 82, 'KIBUNDAIRE BUSEMBYA', 'KBD-BS', '2026-01-27 22:12:52'),
(690, 82, 'LUBANI CENTRAL', 'LBN-C', '2026-01-27 22:12:52'),
(691, 82, 'LUBANI WEST', 'LBN-W', '2026-01-27 22:12:52'),
(692, 83, 'MPUMWIRE CENTRAL', 'MPM-C', '2026-01-27 22:12:52'),
(693, 83, 'KIWUMO', 'KWM', '2026-01-27 22:12:52'),
(694, 83, 'KYEBANDO', 'KYB', '2026-01-27 22:12:52'),
(695, 83, 'NAWAGUMA A', 'NWG-A', '2026-01-27 22:12:52'),
(696, 83, 'NAWAGUMA B', 'NWG-B', '2026-01-27 22:12:52'),
(697, 84, 'NAMWENDWA A', 'NMW-A', '2026-01-27 22:12:52'),
(698, 84, 'NAMWENDWA B', 'NMW-B', '2026-01-27 22:12:52'),
(699, 84, 'NAMWENDWA C', 'NMW-C', '2026-01-27 22:12:52'),
(700, 84, 'NDIWANSI', 'NDW', '2026-01-27 22:12:52'),
(701, 84, 'NVUNWA', 'NVW', '2026-01-27 22:12:52'),
(702, 85, 'BUWEERA EAST', 'BWR-E', '2026-01-27 22:12:52'),
(703, 85, 'BUWEERA WEST', 'BWR-W', '2026-01-27 22:12:52'),
(704, 85, 'BUWOLERO CENTRAL', 'BWL-C', '2026-01-27 22:12:52'),
(705, 85, 'BUWOLERO IGOMBE', 'BWL-I', '2026-01-27 22:12:52'),
(706, 85, 'BUWOLERO KIZINGA', 'BWL-K', '2026-01-27 22:12:52'),
(707, 85, 'BUWOLERO MAWOLERO', 'BWL-M', '2026-01-27 22:12:52'),
(708, 85, 'BUWOLERO NAKULYAKU', 'BWL-N', '2026-01-27 22:12:52'),
(709, 85, 'YUUKA', 'YUK', '2026-01-27 22:12:52'),
(710, 86, 'KAGOMA BUWOLOMERA', 'KGM-B', '2026-01-27 22:12:52'),
(711, 86, 'KAGOMA CENTRAL', 'KGM-C', '2026-01-27 22:12:52'),
(712, 86, 'KAGOMA MAKOTA', 'KGM-M', '2026-01-27 22:12:52'),
(713, 86, 'MUTAI BUSIBE', 'MTI-BS', '2026-01-27 22:12:52'),
(714, 86, 'MUTAI CENTRAL', 'MTI-C', '2026-01-27 22:12:52'),
(715, 86, 'MUTAI KANYALE', 'MTI-K', '2026-01-27 22:12:52'),
(716, 86, 'NAMALERE CENTRAL', 'NML-C', '2026-01-27 22:12:52'),
(717, 86, 'NAMALERE KABAGANDA', 'NML-K', '2026-01-27 22:12:52'),
(718, 86, 'NAMALERE SOUTH', 'NML-S', '2026-01-27 22:12:52'),
(719, 87, 'BUTEGANA EAST', 'BTG-E', '2026-01-27 22:12:52'),
(720, 87, 'BUTEGANA WEST', 'BTG-W', '2026-01-27 22:12:52'),
(721, 87, 'KAIIRA', 'KIR', '2026-01-27 22:12:52'),
(722, 87, 'MAWOITO BUBIRO EAST', 'MWT-BE', '2026-01-27 22:12:52'),
(723, 87, 'MAWOITO BUBIRO WEST', 'MWT-BW', '2026-01-27 22:12:52'),
(724, 87, 'MAWOITO BUKOLOKOTI', 'MWT-BK', '2026-01-27 22:12:52'),
(725, 87, 'MAWOITO BUKYEBAMBE', 'MWT-BY', '2026-01-27 22:12:52'),
(726, 87, 'MAWOITO BUYEMBA', 'MWT-BM', '2026-01-27 22:12:52'),
(727, 87, 'MAWOITO KIGAYA', 'MWT-KG', '2026-01-27 22:12:52'),
(728, 87, 'MUWANGI BUKOLWA', 'MWG-BK', '2026-01-27 22:12:52'),
(729, 87, 'MUWANGI BULAGALA', 'MWG-BL', '2026-01-27 22:12:52'),
(730, 87, 'MUWANGI BULUMBA', 'MWG-BM', '2026-01-27 22:12:52'),
(731, 88, 'BUSIA II', 'BSA-2', '2026-01-27 22:12:52'),
(732, 88, 'IDOOME', 'IDM', '2026-01-27 22:12:52'),
(733, 88, 'ISIRI', 'ISR', '2026-01-27 22:12:52'),
(734, 88, 'KITANABA', 'KTN', '2026-01-27 22:12:52'),
(735, 88, 'MPUNGWE', 'MPG', '2026-01-27 22:12:52'),
(736, 89, 'BUTANGALA A', 'BTG-A', '2026-01-27 22:12:52'),
(737, 89, 'BUTANGALA B', 'BTG-B', '2026-01-27 22:12:52'),
(738, 89, 'BUTANGALA C', 'BTG-C', '2026-01-27 22:12:52'),
(739, 89, 'BUTANGALA D', 'BTG-D', '2026-01-27 22:12:52'),
(740, 89, 'IGOMBE BULAGALA', 'IGB-BL', '2026-01-27 22:12:52'),
(741, 89, 'IGOMBE BUSIGE', 'IGB-BS', '2026-01-27 22:12:52'),
(742, 89, 'KALEBERA EAST', 'KLB-E', '2026-01-27 22:12:52'),
(743, 89, 'KALEBERA WEST', 'KLB-W', '2026-01-27 22:12:52'),
(744, 89, 'KYERINDA SOUTH', 'KYR-S', '2026-01-27 22:12:52'),
(745, 89, 'MAGAMAGA EAST', 'MGM-E', '2026-01-27 22:12:52'),
(746, 89, 'MAGAMAGA WEST', 'MGM-W', '2026-01-27 22:12:52'),
(747, 89, 'MUGULUKA WEST', 'MGK-W', '2026-01-27 22:12:52'),
(748, 89, 'MUGULUKA EAST', 'MGK-E', '2026-01-27 22:12:52'),
(749, 90, 'BUDHUMBULI ZONE', 'BDH', '2026-01-27 22:12:52'),
(750, 90, 'BUSIA ZONE', 'BSA', '2026-01-27 22:12:52'),
(751, 90, 'KILANGIRA ZONE', 'KLG', '2026-01-27 22:12:52'),
(752, 90, 'SWANU ZONE', 'SWN', '2026-01-27 22:12:52'),
(753, 91, 'HOSPITAL ZONE', 'HSP', '2026-01-27 22:12:52'),
(754, 91, 'KALAMOYA ZONE', 'KLM', '2026-01-27 22:12:52'),
(755, 91, 'MUHOFA ZONE', 'MHF', '2026-01-27 22:12:52'),
(756, 91, 'MUKWANGA ZONE', 'MKW', '2026-01-27 22:12:52'),
(757, 91, 'WAMUKOLO ZONE', 'WMK', '2026-01-27 22:12:52'),
(758, 92, 'KADIBA ZONE', 'KDB', '2026-01-27 22:12:52'),
(759, 92, 'KIGENYI ZONE', 'KGY', '2026-01-27 22:12:52'),
(760, 92, 'KYERINDA ZONE', 'KYR', '2026-01-27 22:12:52'),
(761, 92, 'MARKET ZONE', 'MKT', '2026-01-27 22:12:52'),
(762, 92, 'MUNYEGERA ZONE', 'MNY', '2026-01-27 22:12:52'),
(763, 93, 'BWASE', 'BWS', '2026-01-27 22:12:52'),
(764, 93, 'CHURCH ZONE', 'CHR', '2026-01-27 22:12:52'),
(765, 93, 'KABI ZONE', 'KAB', '2026-01-27 22:12:52'),
(766, 93, 'MUZIGITI ZONE', 'MZG', '2026-01-27 22:12:52'),
(767, 94, 'BUDHOBYA CELL', 'BDH', '2026-01-27 22:12:52'),
(768, 94, 'BULAMA A', 'BLM-A', '2026-01-27 22:12:52'),
(769, 94, 'BULAMA B', 'BLM-B', '2026-01-27 22:12:52'),
(770, 94, 'BUSEGULA', 'BSG', '2026-01-27 22:12:52'),
(771, 94, 'KAYALWE A', 'KYL-A', '2026-01-27 22:12:52'),
(772, 94, 'KAYALWE B', 'KYL-B', '2026-01-27 22:12:52'),
(773, 94, 'LWANYAMA', 'LWY', '2026-01-27 22:12:52'),
(774, 94, 'NAKITOKOLO', 'NKT', '2026-01-27 22:12:52'),
(775, 95, 'BUBANDA', 'BBD', '2026-01-27 22:12:52'),
(776, 95, 'BUGONGWE', 'BGW', '2026-01-27 22:12:52'),
(777, 95, 'BUKOLOBOZA', 'BKL', '2026-01-27 22:12:52'),
(778, 95, 'KITUMBUGULU', 'KTM', '2026-01-27 22:12:52'),
(779, 95, 'LWITAMAKOLI', 'LWT', '2026-01-27 22:12:52'),
(780, 95, 'MUSISI', 'MSS', '2026-01-27 22:12:52'),
(781, 95, 'NAMATA', 'NMT', '2026-01-27 22:12:52'),
(782, 95, 'NAWAMBOGA', 'NWM', '2026-01-27 22:12:52'),
(783, 96, 'BUDAALI', 'BDL', '2026-01-27 22:12:52'),
(784, 96, 'BUWABUZI', 'BWB', '2026-01-27 22:12:52'),
(785, 96, 'BUYENGO', 'BYG', '2026-01-27 22:12:52'),
(786, 96, 'KAMIIGO', 'KMG', '2026-01-27 22:12:52'),
(787, 96, 'KANGULUMIRA', 'KGL', '2026-01-27 22:12:52'),
(788, 96, 'LWAMBOGO', 'LWM', '2026-01-27 22:12:52'),
(789, 96, 'NABIGWALI', 'NBG', '2026-01-27 22:12:52'),
(790, 96, 'NAKIVUMBI', 'NKV', '2026-01-27 22:12:52'),
(791, 96, 'NAMISOTA', 'NMS', '2026-01-27 22:12:52'),
(792, 97, 'BALIBONA', 'BLB', '2026-01-27 22:12:52'),
(793, 97, 'BUDHUMBULU', 'BDM', '2026-01-27 22:12:53'),
(794, 97, 'BUKASAMI', 'BKS', '2026-01-27 22:12:53'),
(795, 97, 'BUKYEYUNE', 'BKY', '2026-01-27 22:12:53'),
(796, 97, 'BUYONGO', 'BYG', '2026-01-27 22:12:53'),
(797, 97, 'MBAALE CELL', 'MBL', '2026-01-27 22:12:53'),
(798, 97, 'NABITOSI', 'NBT', '2026-01-27 22:12:53'),
(799, 97, 'NABULAGALA', 'NBL', '2026-01-27 22:12:53'),
(800, 97, 'NABUSAGWA', 'NBS', '2026-01-27 22:12:53'),
(801, 97, 'NAKAJO', 'NKJ', '2026-01-27 22:12:53');

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_active_price_alerts`
-- (See below for the actual view)
--
CREATE TABLE `v_active_price_alerts` (
`id` int(11)
,`user_id` int(11)
,`full_name` varchar(100)
,`phone_number` varchar(15)
,`product_type` varchar(50)
,`target_price` decimal(10,2)
,`alert_condition` enum('above','below')
,`last_triggered` timestamp
,`current_avg_price` decimal(14,6)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_active_products`
-- (See below for the actual view)
--
CREATE TABLE `v_active_products` (
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_admin_users`
-- (See below for the actual view)
--
CREATE TABLE `v_admin_users` (
`id` int(11)
,`full_name` varchar(100)
,`phone_number` varchar(15)
,`email` varchar(100)
,`user_type` enum('farmer','buyer','extension_officer','admin')
,`role_name` varchar(50)
,`role_level` int(11)
,`last_login` timestamp
,`last_activity` timestamp
,`is_active` tinyint(1)
,`created_at` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_ai_performance_metrics`
-- (See below for the actual view)
--
CREATE TABLE `v_ai_performance_metrics` (
`date` date
,`language` varchar(10)
,`source` enum('openai','rule_based','error')
,`total_interactions` bigint(21)
,`openai_usage_percent` decimal(6,2)
,`unique_users` bigint(21)
,`total_sessions` bigint(21)
,`avg_response_length` decimal(10,0)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_ai_popular_topics`
-- (See below for the actual view)
--
CREATE TABLE `v_ai_popular_topics` (
`topic_keywords` mediumtext
,`language` varchar(10)
,`frequency` bigint(21)
,`unique_users` bigint(21)
,`last_asked` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_ai_session_stats`
-- (See below for the actual view)
--
CREATE TABLE `v_ai_session_stats` (
`session_id` varchar(100)
,`user_id` int(11)
,`message_count` bigint(21)
,`session_start` timestamp
,`session_end` timestamp
,`duration_minutes` bigint(21)
,`sources_used` mediumtext
,`avg_response_length` decimal(13,4)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_buyer_purchase_analytics`
-- (See below for the actual view)
--
CREATE TABLE `v_buyer_purchase_analytics` (
`buyer_id` int(11)
,`total_orders` bigint(21)
,`unique_suppliers` bigint(21)
,`total_spent` decimal(32,2)
,`avg_order_value` decimal(14,6)
,`completed_orders` decimal(22,0)
,`cancelled_orders` decimal(22,0)
,`most_purchased_category` enum('sugar_cane','poultry','maize','vegetables','coffee','beans','cassava','bananas','dairy','livestock','other')
,`months_active` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_complete_location_hierarchy`
-- (See below for the actual view)
--
CREATE TABLE `v_complete_location_hierarchy` (
`region_id` int(11)
,`region_name` varchar(100)
,`region_code` varchar(10)
,`district_id` int(11)
,`district_name` varchar(100)
,`district_code` varchar(10)
,`subcounty_id` int(11)
,`subcounty_name` varchar(100)
,`subcounty_code` varchar(10)
,`parish_id` int(11)
,`parish_name` varchar(100)
,`parish_code` varchar(10)
,`village_id` int(11)
,`village_name` varchar(100)
,`village_code` varchar(10)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_encryption_stats`
-- (See below for the actual view)
--
CREATE TABLE `v_encryption_stats` (
`user_id` int(11)
,`full_name` varchar(100)
,`total_encrypted_messages` bigint(21)
,`encrypted_chats` bigint(21)
,`last_encrypted_message` timestamp
,`key_fingerprint` varchar(64)
,`key_created_at` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_extension_performance`
-- (See below for the actual view)
--
CREATE TABLE `v_extension_performance` (
`user_id` int(11)
,`full_name` varchar(100)
,`role_name` varchar(100)
,`assigned_level` enum('national','regional','district','subcounty','parish','village')
,`total_services` bigint(21)
,`completed_services` bigint(21)
,`total_participants` decimal(32,0)
,`average_rating` decimal(14,4)
,`total_activities` bigint(21)
,`total_farmers_reached` decimal(32,0)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_extension_workers`
-- (See below for the actual view)
--
CREATE TABLE `v_extension_workers` (
`user_id` int(11)
,`full_name` varchar(100)
,`phone_number` varchar(15)
,`email` varchar(100)
,`assignment_id` int(11)
,`role_name` varchar(100)
,`role_level` enum('national','regional','district','subcounty','parish','village')
,`organization_type` enum('government','ngo','international','private')
,`organization_name` varchar(200)
,`assigned_level` enum('national','regional','district','subcounty','parish','village')
,`employee_id` varchar(50)
,`start_date` date
,`end_date` date
,`is_active` tinyint(1)
,`region_name` varchar(100)
,`district_name` varchar(100)
,`subcounty_name` varchar(100)
,`parish_name` varchar(100)
,`village_name` varchar(100)
,`supervisor_name` varchar(100)
,`specializations` mediumtext
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_latest_prices`
-- (See below for the actual view)
--
CREATE TABLE `v_latest_prices` (
`product_type` varchar(50)
,`market_location` varchar(100)
,`price` decimal(10,2)
,`unit` varchar(20)
,`source` varchar(100)
,`price_date` date
,`created_at` timestamp
,`rn` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_learned_pattern_effectiveness`
-- (See below for the actual view)
--
CREATE TABLE `v_learned_pattern_effectiveness` (
`id` int(11)
,`question_pattern` text
,`language` enum('en','lusoga')
,`source` enum('openai','user_feedback','admin','system')
,`usage_count` int(11)
,`success_rate` decimal(3,2)
,`feedback_count` bigint(21)
,`helpful_count` decimal(22,0)
,`not_helpful_count` decimal(22,0)
,`last_used` timestamp
,`created_at` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_location_hierarchy`
-- (See below for the actual view)
--
CREATE TABLE `v_location_hierarchy` (
`village_id` int(11)
,`village_name` varchar(100)
,`parish_id` int(11)
,`parish_name` varchar(100)
,`subcounty_id` int(11)
,`subcounty_name` varchar(100)
,`district_id` int(11)
,`district_name` varchar(100)
,`region_id` int(11)
,`region_name` varchar(100)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_order_summary`
-- (See below for the actual view)
--
CREATE TABLE `v_order_summary` (
`id` int(11)
,`order_number` varchar(20)
,`product_id` int(11)
,`buyer_id` int(11)
,`seller_id` int(11)
,`quantity` decimal(10,2)
,`unit_price` decimal(10,2)
,`total_amount` decimal(10,2)
,`delivery_address` text
,`status` enum('pending','confirmed','processing','completed','cancelled')
,`payment_status` enum('unpaid','partial','paid')
,`payment_method` varchar(50)
,`notes` text
,`created_at` timestamp
,`updated_at` timestamp
,`product_name` varchar(100)
,`category` enum('sugar_cane','poultry','maize','vegetables','coffee','beans','cassava','bananas','dairy','livestock','other')
,`buyer_name` varchar(100)
,`buyer_phone` varchar(15)
,`seller_name` varchar(100)
,`seller_phone` varchar(15)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_pending_approvals`
-- (See below for the actual view)
--
CREATE TABLE `v_pending_approvals` (
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_price_trends`
-- (See below for the actual view)
--
CREATE TABLE `v_price_trends` (
`product_type` varchar(50)
,`month` varchar(7)
,`avg_price` decimal(14,6)
,`min_price` decimal(10,2)
,`max_price` decimal(10,2)
,`price_count` bigint(21)
,`price_volatility` double(26,6)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_recent_admin_activities`
-- (See below for the actual view)
--
CREATE TABLE `v_recent_admin_activities` (
`id` int(11)
,`admin_id` int(11)
,`action_type` varchar(100)
,`action_description` text
,`affected_table` varchar(50)
,`affected_record_id` int(11)
,`ip_address` varchar(45)
,`user_agent` text
,`request_data` longtext
,`created_at` timestamp
,`admin_name` varchar(100)
,`admin_role` varchar(50)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_recent_market_prices`
-- (See below for the actual view)
--
CREATE TABLE `v_recent_market_prices` (
`product_type` varchar(50)
,`market_location` varchar(100)
,`price` decimal(10,2)
,`unit` varchar(20)
,`source` varchar(100)
,`price_date` date
,`rn` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_role_permission_summary`
-- (See below for the actual view)
--
CREATE TABLE `v_role_permission_summary` (
`role_id` int(11)
,`role_name` varchar(50)
,`role_level` int(11)
,`permissions_count` bigint(21)
,`categories` mediumtext
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_supplier_performance`
-- (See below for the actual view)
--
CREATE TABLE `v_supplier_performance` (
`seller_id` int(11)
,`buyer_id` int(11)
,`supplier_name` varchar(100)
,`total_orders` bigint(21)
,`total_value` decimal(32,2)
,`avg_rating` decimal(7,6)
,`successful_deliveries` decimal(22,0)
,`cancelled_orders` decimal(22,0)
,`last_order_date` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_upcoming_services`
-- (See below for the actual view)
--
CREATE TABLE `v_upcoming_services` (
`id` int(11)
,`officer_id` int(11)
,`service_type` enum('farm_visit','training','consultation','demonstration')
,`title` varchar(200)
,`description` text
,`location` varchar(100)
,`scheduled_date` date
,`scheduled_time` time
,`duration_hours` int(11)
,`max_participants` int(11)
,`status` enum('scheduled','ongoing','completed','cancelled')
,`created_at` timestamp
,`updated_at` timestamp
,`officer_name` varchar(100)
,`officer_phone` varchar(15)
,`registered_participants` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_user_complete_profile`
-- (See below for the actual view)
--
CREATE TABLE `v_user_complete_profile` (
`id` int(11)
,`phone_number` varchar(15)
,`full_name` varchar(100)
,`email` varchar(100)
,`user_type` enum('farmer','buyer','extension_officer','admin')
,`is_verified` tinyint(1)
,`profile_picture` varchar(255)
,`joined_date` timestamp
,`last_login` timestamp
,`region_name` varchar(100)
,`district_name` varchar(100)
,`subcounty_name` varchar(100)
,`parish_name` varchar(100)
,`village_name` varchar(100)
,`bio` text
,`tagline` varchar(200)
,`about_me` text
,`cover_photo` varchar(255)
,`date_of_birth` date
,`gender` enum('male','female','other','prefer_not_to_say')
,`occupation` varchar(100)
,`education_level` enum('primary','secondary','certificate','diploma','degree','masters','phd')
,`years_in_farming` int(11)
,`farm_size_acres` decimal(10,2)
,`farming_type` enum('subsistence','commercial','mixed','organic')
,`profile_views` int(11)
,`profile_completeness` int(11)
,`facebook_url` varchar(255)
,`twitter_url` varchar(255)
,`instagram_url` varchar(255)
,`linkedin_url` varchar(255)
,`show_phone` tinyint(1)
,`show_location` tinyint(1)
,`show_email` tinyint(1)
,`show_birthday` tinyint(1)
,`profile_visibility` enum('public','friends','private')
,`friends_count` bigint(21)
,`active_products_count` bigint(21)
,`posts_count` bigint(21)
,`average_rating` decimal(14,4)
,`review_count` bigint(21)
,`achievements_count` bigint(21)
,`photos_count` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_user_one_on_one_chats`
-- (See below for the actual view)
--
CREATE TABLE `v_user_one_on_one_chats` (
`chat_id` int(11)
,`chat_created_at` timestamp
,`chat_updated_at` timestamp
,`user_id` int(11)
,`friend_id` int(11)
,`friend_name` varchar(100)
,`friend_avatar` varchar(255)
,`friend_last_activity` timestamp
,`is_online` int(1)
,`last_message` mediumtext
,`last_message_time` timestamp
,`unread_count` bigint(21)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_user_permissions`
-- (See below for the actual view)
--
CREATE TABLE `v_user_permissions` (
`user_id` int(11)
,`full_name` varchar(100)
,`role_name` varchar(50)
,`role_level` int(11)
,`permission_key` varchar(50)
,`permission_name` varchar(100)
,`granted_at` timestamp
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_user_photos_status`
-- (See below for the actual view)
--
CREATE TABLE `v_user_photos_status` (
`user_id` int(11)
,`full_name` varchar(100)
,`users_profile_pic` varchar(255)
,`profiles_cover_photo` varchar(255)
,`profile_photo_id` int(11)
,`profile_photo_url` varchar(255)
,`profile_is_current` tinyint(1)
,`cover_photo_id` int(11)
,`cover_photo_url` varchar(255)
,`cover_is_current` tinyint(1)
);

-- --------------------------------------------------------

--
-- Stand-in structure for view `v_user_statistics`
-- (See below for the actual view)
--
CREATE TABLE `v_user_statistics` (
`user_id` int(11)
,`full_name` varchar(100)
,`user_type` enum('farmer','buyer','extension_officer','admin')
,`total_farms` bigint(21)
,`total_enterprises` bigint(21)
,`total_products` bigint(21)
,`total_friends` bigint(21)
,`average_rating` decimal(14,4)
,`total_reviews` bigint(21)
);

-- --------------------------------------------------------

--
-- Table structure for table `weather_data`
--

CREATE TABLE `weather_data` (
  `id` int(11) NOT NULL,
  `location` varchar(100) NOT NULL,
  `temperature` decimal(5,2) DEFAULT NULL,
  `humidity` decimal(5,2) DEFAULT NULL,
  `rainfall` decimal(10,2) DEFAULT NULL,
  `weather_condition` varchar(50) DEFAULT NULL,
  `forecast_date` date NOT NULL,
  `is_forecast` tinyint(1) DEFAULT 0,
  `source` varchar(100) DEFAULT 'API',
  `created_at` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Structure for view `v_active_price_alerts`
--
DROP TABLE IF EXISTS `v_active_price_alerts`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_active_price_alerts`  AS SELECT `pa`.`id` AS `id`, `pa`.`user_id` AS `user_id`, `u`.`full_name` AS `full_name`, `u`.`phone_number` AS `phone_number`, `pa`.`product_type` AS `product_type`, `pa`.`target_price` AS `target_price`, `pa`.`alert_condition` AS `alert_condition`, `pa`.`last_triggered` AS `last_triggered`, (select avg(`mp`.`price`) from `market_prices` `mp` where `mp`.`product_type` = `pa`.`product_type` and `mp`.`price_date` >= curdate() - interval 7 day) AS `current_avg_price` FROM (`price_alerts` `pa` join `users` `u` on(`pa`.`user_id` = `u`.`id`)) WHERE `pa`.`is_active` = 1 ;

-- --------------------------------------------------------

--
-- Structure for view `v_active_products`
--
DROP TABLE IF EXISTS `v_active_products`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_active_products`  AS SELECT `p`.`id` AS `id`, `p`.`seller_id` AS `seller_id`, `p`.`enterprise_id` AS `enterprise_id`, `p`.`product_name` AS `product_name`, `p`.`category` AS `category`, `p`.`description` AS `description`, `p`.`quantity` AS `quantity`, `p`.`unit` AS `unit`, `p`.`price_per_unit` AS `price_per_unit`, `p`.`location` AS `location`, `p`.`images` AS `images`, `p`.`status` AS `status`, `p`.`views` AS `views`, `p`.`created_at` AS `created_at`, `p`.`updated_at` AS `updated_at`, `p`.`expires_at` AS `expires_at`, `u`.`full_name` AS `seller_name`, `u`.`phone_number` AS `seller_phone`, `u`.`village` AS `village`, `u`.`subcounty` AS `subcounty`, `u`.`district` AS `district`, (select avg(`reviews`.`rating`) from `reviews` where `reviews`.`reviewed_user_id` = `u`.`id`) AS `seller_rating`, (select count(0) from `reviews` where `reviews`.`reviewed_user_id` = `u`.`id`) AS `seller_review_count` FROM (`products` `p` join `users` `u` on(`p`.`seller_id` = `u`.`id`)) WHERE `p`.`status` = 'available' ;

-- --------------------------------------------------------

--
-- Structure for view `v_admin_users`
--
DROP TABLE IF EXISTS `v_admin_users`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_admin_users`  AS SELECT `u`.`id` AS `id`, `u`.`full_name` AS `full_name`, `u`.`phone_number` AS `phone_number`, `u`.`email` AS `email`, `u`.`user_type` AS `user_type`, `ar`.`role_name` AS `role_name`, `ar`.`role_level` AS `role_level`, `u`.`last_login` AS `last_login`, `u`.`last_activity` AS `last_activity`, `u`.`is_active` AS `is_active`, `u`.`created_at` AS `created_at` FROM (`users` `u` left join `admin_roles` `ar` on(`u`.`admin_role_id` = `ar`.`id`)) WHERE `u`.`user_type` in ('admin','super_admin') ORDER BY `ar`.`role_level` DESC, `u`.`full_name` ASC ;

-- --------------------------------------------------------

--
-- Structure for view `v_ai_performance_metrics`
--
DROP TABLE IF EXISTS `v_ai_performance_metrics`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_ai_performance_metrics`  AS SELECT cast(`ai_conversations`.`created_at` as date) AS `date`, `ai_conversations`.`language` AS `language`, `ai_conversations`.`source` AS `source`, count(0) AS `total_interactions`, round(avg(case when `ai_conversations`.`source` = 'openai' then 1 else 0 end) * 100,2) AS `openai_usage_percent`, count(distinct `ai_conversations`.`user_id`) AS `unique_users`, count(distinct `ai_conversations`.`session_id`) AS `total_sessions`, round(avg(char_length(`ai_conversations`.`response`)),0) AS `avg_response_length` FROM `ai_conversations` WHERE `ai_conversations`.`created_at` >= curdate() - interval 30 day GROUP BY cast(`ai_conversations`.`created_at` as date), `ai_conversations`.`language`, `ai_conversations`.`source` ORDER BY cast(`ai_conversations`.`created_at` as date) DESC, `ai_conversations`.`language` ASC, `ai_conversations`.`source` ASC ;

-- --------------------------------------------------------

--
-- Structure for view `v_ai_popular_topics`
--
DROP TABLE IF EXISTS `v_ai_popular_topics`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_ai_popular_topics`  AS SELECT lcase(substring_index(substring_index(`ai_conversations`.`message`,' ',3),' ',-3)) AS `topic_keywords`, `ai_conversations`.`language` AS `language`, count(0) AS `frequency`, count(distinct `ai_conversations`.`user_id`) AS `unique_users`, max(`ai_conversations`.`created_at`) AS `last_asked` FROM `ai_conversations` WHERE `ai_conversations`.`created_at` >= curdate() - interval 7 day AND `ai_conversations`.`message` is not null GROUP BY lcase(substring_index(substring_index(`ai_conversations`.`message`,' ',3),' ',-3)), `ai_conversations`.`language` HAVING `frequency` > 2 ORDER BY count(0) DESC LIMIT 0, 50 ;

-- --------------------------------------------------------

--
-- Structure for view `v_ai_session_stats`
--
DROP TABLE IF EXISTS `v_ai_session_stats`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_ai_session_stats`  AS SELECT `ai_conversations`.`session_id` AS `session_id`, `ai_conversations`.`user_id` AS `user_id`, count(0) AS `message_count`, min(`ai_conversations`.`created_at`) AS `session_start`, max(`ai_conversations`.`created_at`) AS `session_end`, timestampdiff(MINUTE,min(`ai_conversations`.`created_at`),max(`ai_conversations`.`created_at`)) AS `duration_minutes`, group_concat(distinct `ai_conversations`.`source` order by `ai_conversations`.`created_at` ASC separator ',') AS `sources_used`, avg(char_length(`ai_conversations`.`response`)) AS `avg_response_length` FROM `ai_conversations` WHERE `ai_conversations`.`session_id` is not null GROUP BY `ai_conversations`.`session_id`, `ai_conversations`.`user_id` ORDER BY max(`ai_conversations`.`created_at`) DESC ;

-- --------------------------------------------------------

--
-- Structure for view `v_buyer_purchase_analytics`
--
DROP TABLE IF EXISTS `v_buyer_purchase_analytics`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_buyer_purchase_analytics`  AS SELECT `o`.`buyer_id` AS `buyer_id`, count(distinct `o`.`id`) AS `total_orders`, count(distinct `o`.`seller_id`) AS `unique_suppliers`, sum(`o`.`total_amount`) AS `total_spent`, avg(`o`.`total_amount`) AS `avg_order_value`, sum(case when `o`.`status` = 'completed' then 1 else 0 end) AS `completed_orders`, sum(case when `o`.`status` = 'cancelled' then 1 else 0 end) AS `cancelled_orders`, `p`.`category` AS `most_purchased_category`, count(distinct date_format(`o`.`created_at`,'%Y-%m')) AS `months_active` FROM (`orders` `o` join `products` `p` on(`o`.`product_id` = `p`.`id`)) GROUP BY `o`.`buyer_id`, `p`.`category` ;

-- --------------------------------------------------------

--
-- Structure for view `v_complete_location_hierarchy`
--
DROP TABLE IF EXISTS `v_complete_location_hierarchy`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_complete_location_hierarchy`  AS SELECT `r`.`id` AS `region_id`, `r`.`region_name` AS `region_name`, `r`.`region_code` AS `region_code`, `d`.`id` AS `district_id`, `d`.`district_name` AS `district_name`, `d`.`district_code` AS `district_code`, `s`.`id` AS `subcounty_id`, `s`.`subcounty_name` AS `subcounty_name`, `s`.`subcounty_code` AS `subcounty_code`, `p`.`id` AS `parish_id`, `p`.`parish_name` AS `parish_name`, `p`.`parish_code` AS `parish_code`, `v`.`id` AS `village_id`, `v`.`village_name` AS `village_name`, `v`.`village_code` AS `village_code` FROM ((((`regions` `r` left join `districts` `d` on(`r`.`id` = `d`.`region_id`)) left join `subcounties` `s` on(`d`.`id` = `s`.`district_id`)) left join `parishes` `p` on(`s`.`id` = `p`.`subcounty_id`)) left join `villages` `v` on(`p`.`id` = `v`.`parish_id`)) ORDER BY `r`.`region_name` ASC, `d`.`district_name` ASC, `s`.`subcounty_name` ASC, `p`.`parish_name` ASC, `v`.`village_name` ASC ;

-- --------------------------------------------------------

--
-- Structure for view `v_encryption_stats`
--
DROP TABLE IF EXISTS `v_encryption_stats`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_encryption_stats`  AS SELECT `u`.`id` AS `user_id`, `u`.`full_name` AS `full_name`, count(distinct `m`.`id`) AS `total_encrypted_messages`, count(distinct `m`.`chat_id`) AS `encrypted_chats`, max(`m`.`created_at`) AS `last_encrypted_message`, `uek`.`fingerprint` AS `key_fingerprint`, `uek`.`created_at` AS `key_created_at` FROM ((`users` `u` left join `user_encryption_keys` `uek` on(`u`.`id` = `uek`.`user_id`)) left join `messages` `m` on(`u`.`id` = `m`.`sender_id` and `m`.`is_encrypted` = 1)) WHERE `uek`.`id` is not null GROUP BY `u`.`id` ;

-- --------------------------------------------------------

--
-- Structure for view `v_extension_performance`
--
DROP TABLE IF EXISTS `v_extension_performance`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_extension_performance`  AS SELECT `ea`.`user_id` AS `user_id`, `u`.`full_name` AS `full_name`, `er`.`role_name` AS `role_name`, `ea`.`assigned_level` AS `assigned_level`, count(distinct `es`.`id`) AS `total_services`, count(distinct case when `es`.`status` = 'completed' then `es`.`id` end) AS `completed_services`, sum(distinct case when `es`.`status` = 'completed' then `sp`.`id` end) AS `total_participants`, avg(`sp`.`rating`) AS `average_rating`, count(distinct `eal`.`id`) AS `total_activities`, sum(`eal`.`farmers_reached`) AS `total_farmers_reached` FROM (((((`extension_assignments` `ea` join `users` `u` on(`ea`.`user_id` = `u`.`id`)) join `extension_roles` `er` on(`ea`.`role_id` = `er`.`id`)) left join `extension_services` `es` on(`ea`.`user_id` = `es`.`officer_id`)) left join `service_participants` `sp` on(`es`.`id` = `sp`.`service_id`)) left join `extension_activity_log` `eal` on(`ea`.`user_id` = `eal`.`user_id`)) WHERE `ea`.`is_active` = 1 GROUP BY `ea`.`user_id` ;

-- --------------------------------------------------------

--
-- Structure for view `v_extension_workers`
--
DROP TABLE IF EXISTS `v_extension_workers`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_extension_workers`  AS SELECT `u`.`id` AS `user_id`, `u`.`full_name` AS `full_name`, `u`.`phone_number` AS `phone_number`, `u`.`email` AS `email`, `ea`.`id` AS `assignment_id`, `er`.`role_name` AS `role_name`, `er`.`role_level` AS `role_level`, `er`.`organization_type` AS `organization_type`, `ea`.`organization_name` AS `organization_name`, `ea`.`assigned_level` AS `assigned_level`, `ea`.`employee_id` AS `employee_id`, `ea`.`start_date` AS `start_date`, `ea`.`end_date` AS `end_date`, `ea`.`is_active` AS `is_active`, `r`.`region_name` AS `region_name`, `d`.`district_name` AS `district_name`, `s`.`subcounty_name` AS `subcounty_name`, `p`.`parish_name` AS `parish_name`, `v`.`village_name` AS `village_name`, `supervisor`.`full_name` AS `supervisor_name`, (select group_concat(`es`.`specialization_name` separator ', ') from `extension_specializations` `es` where `es`.`assignment_id` = `ea`.`id`) AS `specializations` FROM ((((((((`users` `u` join `extension_assignments` `ea` on(`u`.`id` = `ea`.`user_id`)) join `extension_roles` `er` on(`ea`.`role_id` = `er`.`id`)) left join `regions` `r` on(`ea`.`region_id` = `r`.`id`)) left join `districts` `d` on(`ea`.`district_id` = `d`.`id`)) left join `subcounties` `s` on(`ea`.`subcounty_id` = `s`.`id`)) left join `parishes` `p` on(`ea`.`parish_id` = `p`.`id`)) left join `villages` `v` on(`ea`.`village_id` = `v`.`id`)) left join `users` `supervisor` on(`ea`.`supervisor_id` = `supervisor`.`id`)) WHERE `u`.`user_type` = 'extension_officer' ;

-- --------------------------------------------------------

--
-- Structure for view `v_latest_prices`
--
DROP TABLE IF EXISTS `v_latest_prices`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_latest_prices`  AS SELECT `mp`.`product_type` AS `product_type`, `mp`.`market_location` AS `market_location`, `mp`.`price` AS `price`, `mp`.`unit` AS `unit`, `mp`.`source` AS `source`, `mp`.`price_date` AS `price_date`, `mp`.`created_at` AS `created_at`, row_number() over ( partition by `mp`.`product_type`,`mp`.`market_location` order by `mp`.`price_date` desc) AS `rn` FROM `market_prices` AS `mp` WHERE `mp`.`price_date` >= curdate() - interval 30 day ;

-- --------------------------------------------------------

--
-- Structure for view `v_learned_pattern_effectiveness`
--
DROP TABLE IF EXISTS `v_learned_pattern_effectiveness`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_learned_pattern_effectiveness`  AS SELECT `lp`.`id` AS `id`, `lp`.`question_pattern` AS `question_pattern`, `lp`.`language` AS `language`, `lp`.`source` AS `source`, `lp`.`usage_count` AS `usage_count`, `lp`.`success_rate` AS `success_rate`, count(distinct `cf`.`id`) AS `feedback_count`, sum(case when `cf`.`rating` = 'helpful' then 1 else 0 end) AS `helpful_count`, sum(case when `cf`.`rating` = 'not_helpful' then 1 else 0 end) AS `not_helpful_count`, `lp`.`last_used` AS `last_used`, `lp`.`created_at` AS `created_at` FROM ((`ai_learned_patterns` `lp` left join `ai_conversations` `ac` on(lcase(`ac`.`message`) like concat('%',lcase(substr(`lp`.`question_pattern`,1,20)),'%'))) left join `ai_conversation_feedback` `cf` on(`ac`.`id` = `cf`.`conversation_id`)) WHERE `lp`.`is_active` = 1 GROUP BY `lp`.`id` ORDER BY `lp`.`usage_count` DESC, `lp`.`success_rate` DESC ;

-- --------------------------------------------------------

--
-- Structure for view `v_location_hierarchy`
--
DROP TABLE IF EXISTS `v_location_hierarchy`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_location_hierarchy`  AS SELECT `v`.`id` AS `village_id`, `v`.`village_name` AS `village_name`, `p`.`id` AS `parish_id`, `p`.`parish_name` AS `parish_name`, `s`.`id` AS `subcounty_id`, `s`.`subcounty_name` AS `subcounty_name`, `d`.`id` AS `district_id`, `d`.`district_name` AS `district_name`, `r`.`id` AS `region_id`, `r`.`region_name` AS `region_name` FROM ((((`villages` `v` join `parishes` `p` on(`v`.`parish_id` = `p`.`id`)) join `subcounties` `s` on(`p`.`subcounty_id` = `s`.`id`)) join `districts` `d` on(`s`.`district_id` = `d`.`id`)) join `regions` `r` on(`d`.`region_id` = `r`.`id`)) ;

-- --------------------------------------------------------

--
-- Structure for view `v_order_summary`
--
DROP TABLE IF EXISTS `v_order_summary`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_order_summary`  AS SELECT `o`.`id` AS `id`, `o`.`order_number` AS `order_number`, `o`.`product_id` AS `product_id`, `o`.`buyer_id` AS `buyer_id`, `o`.`seller_id` AS `seller_id`, `o`.`quantity` AS `quantity`, `o`.`unit_price` AS `unit_price`, `o`.`total_amount` AS `total_amount`, `o`.`delivery_address` AS `delivery_address`, `o`.`status` AS `status`, `o`.`payment_status` AS `payment_status`, `o`.`payment_method` AS `payment_method`, `o`.`notes` AS `notes`, `o`.`created_at` AS `created_at`, `o`.`updated_at` AS `updated_at`, `p`.`product_name` AS `product_name`, `p`.`category` AS `category`, `buyer`.`full_name` AS `buyer_name`, `buyer`.`phone_number` AS `buyer_phone`, `seller`.`full_name` AS `seller_name`, `seller`.`phone_number` AS `seller_phone` FROM (((`orders` `o` join `products` `p` on(`o`.`product_id` = `p`.`id`)) join `users` `buyer` on(`o`.`buyer_id` = `buyer`.`id`)) join `users` `seller` on(`o`.`seller_id` = `seller`.`id`)) ;

-- --------------------------------------------------------

--
-- Structure for view `v_pending_approvals`
--
DROP TABLE IF EXISTS `v_pending_approvals`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_pending_approvals`  AS SELECT `ua`.`id` AS `id`, `ua`.`user_id` AS `user_id`, `ua`.`user_type` AS `user_type`, `ua`.`approval_status` AS `approval_status`, `ua`.`supporting_documents` AS `supporting_documents`, `ua`.`business_name` AS `business_name`, `ua`.`business_registration` AS `business_registration`, `ua`.`tax_id` AS `tax_id`, `ua`.`qualification_documents` AS `qualification_documents`, `ua`.`rejection_reason` AS `rejection_reason`, `ua`.`approved_by` AS `approved_by`, `ua`.`approved_at` AS `approved_at`, `ua`.`created_at` AS `created_at`, `ua`.`updated_at` AS `updated_at`, `u`.`full_name` AS `full_name`, `u`.`phone_number` AS `phone_number`, `u`.`email` AS `email`, `u`.`district` AS `district`, `u`.`subcounty` AS `subcounty`, `u`.`village` AS `village`, `u`.`created_at` AS `registration_date`, CASE WHEN `ua`.`user_type` = 'buyer' THEN `bp`.`business_name` WHEN `ua`.`user_type` = 'extension_officer' THEN `eo`.`organization` ELSE NULL END AS `organization_name` FROM (((`user_approvals` `ua` join `users` `u` on(`ua`.`user_id` = `u`.`id`)) left join `buyer_profiles` `bp` on(`u`.`id` = `bp`.`user_id`)) left join `extension_officer_profiles` `eo` on(`u`.`id` = `eo`.`user_id`)) WHERE `ua`.`approval_status` = 'pending' ORDER BY `ua`.`created_at` DESC ;

-- --------------------------------------------------------

--
-- Structure for view `v_price_trends`
--
DROP TABLE IF EXISTS `v_price_trends`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_price_trends`  AS SELECT `market_prices`.`product_type` AS `product_type`, date_format(`market_prices`.`price_date`,'%Y-%m') AS `month`, avg(`market_prices`.`price`) AS `avg_price`, min(`market_prices`.`price`) AS `min_price`, max(`market_prices`.`price`) AS `max_price`, count(0) AS `price_count`, std(`market_prices`.`price`) AS `price_volatility` FROM `market_prices` WHERE `market_prices`.`price_date` >= curdate() - interval 12 month GROUP BY `market_prices`.`product_type`, date_format(`market_prices`.`price_date`,'%Y-%m') ORDER BY `market_prices`.`product_type` ASC, date_format(`market_prices`.`price_date`,'%Y-%m') DESC ;

-- --------------------------------------------------------

--
-- Structure for view `v_recent_admin_activities`
--
DROP TABLE IF EXISTS `v_recent_admin_activities`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_recent_admin_activities`  AS SELECT `aal`.`id` AS `id`, `aal`.`admin_id` AS `admin_id`, `aal`.`action_type` AS `action_type`, `aal`.`action_description` AS `action_description`, `aal`.`affected_table` AS `affected_table`, `aal`.`affected_record_id` AS `affected_record_id`, `aal`.`ip_address` AS `ip_address`, `aal`.`user_agent` AS `user_agent`, `aal`.`request_data` AS `request_data`, `aal`.`created_at` AS `created_at`, `u`.`full_name` AS `admin_name`, `ar`.`role_name` AS `admin_role` FROM ((`admin_activity_log` `aal` join `users` `u` on(`aal`.`admin_id` = `u`.`id`)) left join `admin_roles` `ar` on(`u`.`admin_role_id` = `ar`.`id`)) ORDER BY `aal`.`created_at` DESC LIMIT 0, 100 ;

-- --------------------------------------------------------

--
-- Structure for view `v_recent_market_prices`
--
DROP TABLE IF EXISTS `v_recent_market_prices`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_recent_market_prices`  AS SELECT `market_prices`.`product_type` AS `product_type`, `market_prices`.`market_location` AS `market_location`, `market_prices`.`price` AS `price`, `market_prices`.`unit` AS `unit`, `market_prices`.`source` AS `source`, `market_prices`.`price_date` AS `price_date`, row_number() over ( partition by `market_prices`.`product_type` order by `market_prices`.`price_date` desc) AS `rn` FROM `market_prices` WHERE `market_prices`.`price_date` >= curdate() - interval 30 day ;

-- --------------------------------------------------------

--
-- Structure for view `v_role_permission_summary`
--
DROP TABLE IF EXISTS `v_role_permission_summary`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_role_permission_summary`  AS SELECT `ar`.`id` AS `role_id`, `ar`.`role_name` AS `role_name`, `ar`.`role_level` AS `role_level`, count(`rp`.`id`) AS `permissions_count`, group_concat(distinct `ap`.`permission_category` separator ',') AS `categories` FROM ((`admin_roles` `ar` left join `role_permissions` `rp` on(`rp`.`role_id` = `ar`.`id`)) left join `admin_permissions` `ap` on(`ap`.`id` = `rp`.`permission_id`)) GROUP BY `ar`.`id` ;

-- --------------------------------------------------------

--
-- Structure for view `v_supplier_performance`
--
DROP TABLE IF EXISTS `v_supplier_performance`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_supplier_performance`  AS SELECT `o`.`seller_id` AS `seller_id`, `o`.`buyer_id` AS `buyer_id`, `u`.`full_name` AS `supplier_name`, count(`o`.`id`) AS `total_orders`, sum(`o`.`total_amount`) AS `total_value`, avg(`sr`.`overall_rating`) AS `avg_rating`, sum(case when `o`.`status` = 'completed' then 1 else 0 end) AS `successful_deliveries`, sum(case when `o`.`status` = 'cancelled' then 1 else 0 end) AS `cancelled_orders`, max(`o`.`created_at`) AS `last_order_date` FROM ((`orders` `o` join `users` `u` on(`o`.`seller_id` = `u`.`id`)) left join `supplier_ratings` `sr` on(`o`.`seller_id` = `sr`.`supplier_id` and `o`.`buyer_id` = `sr`.`buyer_id`)) GROUP BY `o`.`seller_id`, `o`.`buyer_id` ;

-- --------------------------------------------------------

--
-- Structure for view `v_upcoming_services`
--
DROP TABLE IF EXISTS `v_upcoming_services`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_upcoming_services`  AS SELECT `es`.`id` AS `id`, `es`.`officer_id` AS `officer_id`, `es`.`service_type` AS `service_type`, `es`.`title` AS `title`, `es`.`description` AS `description`, `es`.`location` AS `location`, `es`.`scheduled_date` AS `scheduled_date`, `es`.`scheduled_time` AS `scheduled_time`, `es`.`duration_hours` AS `duration_hours`, `es`.`max_participants` AS `max_participants`, `es`.`status` AS `status`, `es`.`created_at` AS `created_at`, `es`.`updated_at` AS `updated_at`, `u`.`full_name` AS `officer_name`, `u`.`phone_number` AS `officer_phone`, count(`sp`.`id`) AS `registered_participants` FROM ((`extension_services` `es` join `users` `u` on(`es`.`officer_id` = `u`.`id`)) left join `service_participants` `sp` on(`es`.`id` = `sp`.`service_id`)) WHERE `es`.`status` = 'scheduled' AND `es`.`scheduled_date` >= curdate() GROUP BY `es`.`id` ;

-- --------------------------------------------------------

--
-- Structure for view `v_user_complete_profile`
--
DROP TABLE IF EXISTS `v_user_complete_profile`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_user_complete_profile`  AS SELECT `u`.`id` AS `id`, `u`.`phone_number` AS `phone_number`, `u`.`full_name` AS `full_name`, `u`.`email` AS `email`, `u`.`user_type` AS `user_type`, `u`.`is_verified` AS `is_verified`, `u`.`profile_picture` AS `profile_picture`, `u`.`created_at` AS `joined_date`, `u`.`last_login` AS `last_login`, `r`.`region_name` AS `region_name`, `d`.`district_name` AS `district_name`, `s`.`subcounty_name` AS `subcounty_name`, `p`.`parish_name` AS `parish_name`, `v`.`village_name` AS `village_name`, `up`.`bio` AS `bio`, `up`.`tagline` AS `tagline`, `up`.`about_me` AS `about_me`, `up`.`cover_photo` AS `cover_photo`, `up`.`date_of_birth` AS `date_of_birth`, `up`.`gender` AS `gender`, `up`.`occupation` AS `occupation`, `up`.`education_level` AS `education_level`, `up`.`years_in_farming` AS `years_in_farming`, `up`.`farm_size_acres` AS `farm_size_acres`, `up`.`farming_type` AS `farming_type`, `up`.`profile_views` AS `profile_views`, `up`.`profile_completeness` AS `profile_completeness`, `up`.`facebook_url` AS `facebook_url`, `up`.`twitter_url` AS `twitter_url`, `up`.`instagram_url` AS `instagram_url`, `up`.`linkedin_url` AS `linkedin_url`, `up`.`show_phone` AS `show_phone`, `up`.`show_location` AS `show_location`, `up`.`show_email` AS `show_email`, `up`.`show_birthday` AS `show_birthday`, `up`.`profile_visibility` AS `profile_visibility`, (select count(0) from `friendships` where (`friendships`.`user_id` = `u`.`id` or `friendships`.`friend_id` = `u`.`id`) and `friendships`.`status` = 'accepted') AS `friends_count`, (select count(0) from `products` where `products`.`seller_id` = `u`.`id` and `products`.`status` = 'available') AS `active_products_count`, (select count(0) from `posts` where `posts`.`user_id` = `u`.`id`) AS `posts_count`, (select coalesce(avg(`reviews`.`rating`),0) from `reviews` where `reviews`.`reviewed_user_id` = `u`.`id`) AS `average_rating`, (select count(0) from `reviews` where `reviews`.`reviewed_user_id` = `u`.`id`) AS `review_count`, (select count(0) from `user_achievements` where `user_achievements`.`user_id` = `u`.`id`) AS `achievements_count`, (select count(0) from `profile_photos` where `profile_photos`.`user_id` = `u`.`id` and `profile_photos`.`photo_type` = 'gallery') AS `photos_count` 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 `user_profiles` `up` on(`u`.`id` = `up`.`user_id`)) ;

-- --------------------------------------------------------

--
-- Structure for view `v_user_one_on_one_chats`
--
DROP TABLE IF EXISTS `v_user_one_on_one_chats`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_user_one_on_one_chats`  AS SELECT `c`.`id` AS `chat_id`, `c`.`created_at` AS `chat_created_at`, `c`.`updated_at` AS `chat_updated_at`, `cm1`.`user_id` AS `user_id`, `cm2`.`user_id` AS `friend_id`, `u2`.`full_name` AS `friend_name`, `u2`.`profile_picture` AS `friend_avatar`, `u2`.`last_activity` AS `friend_last_activity`, timestampdiff(MINUTE,`u2`.`last_activity`,current_timestamp()) < 5 AS `is_online`, (select `messages`.`content` from `messages` where `messages`.`chat_id` = `c`.`id` order by `messages`.`created_at` desc limit 1) AS `last_message`, (select `messages`.`created_at` from `messages` where `messages`.`chat_id` = `c`.`id` order by `messages`.`created_at` desc limit 1) AS `last_message_time`, (select count(0) from `messages` where `messages`.`chat_id` = `c`.`id` and `messages`.`receiver_id` = `cm1`.`user_id` and `messages`.`created_at` > coalesce(`cm1`.`last_read_at`,'1970-01-01')) AS `unread_count` FROM (((`chats` `c` join `chat_members` `cm1` on(`c`.`id` = `cm1`.`chat_id`)) join `chat_members` `cm2` on(`c`.`id` = `cm2`.`chat_id` and `cm2`.`user_id` <> `cm1`.`user_id`)) join `users` `u2` on(`cm2`.`user_id` = `u2`.`id`)) WHERE `c`.`chat_type` = 'one_to_one' ;

-- --------------------------------------------------------

--
-- Structure for view `v_user_permissions`
--
DROP TABLE IF EXISTS `v_user_permissions`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_user_permissions`  AS SELECT `u`.`id` AS `user_id`, `u`.`full_name` AS `full_name`, `ar`.`role_name` AS `role_name`, `ar`.`role_level` AS `role_level`, `ap`.`permission_key` AS `permission_key`, `ap`.`permission_name` AS `permission_name`, `rp`.`granted_at` AS `granted_at` FROM (((`users` `u` join `admin_roles` `ar` on(`ar`.`id` = `u`.`admin_role_id`)) join `role_permissions` `rp` on(`rp`.`role_id` = `ar`.`id`)) join `admin_permissions` `ap` on(`ap`.`id` = `rp`.`permission_id`)) WHERE `u`.`user_type` = 'admin' AND `u`.`is_active` = 1 ;

-- --------------------------------------------------------

--
-- Structure for view `v_user_photos_status`
--
DROP TABLE IF EXISTS `v_user_photos_status`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_user_photos_status`  AS SELECT `u`.`id` AS `user_id`, `u`.`full_name` AS `full_name`, `u`.`profile_picture` AS `users_profile_pic`, `up`.`cover_photo` AS `profiles_cover_photo`, `pp_profile`.`id` AS `profile_photo_id`, `pp_profile`.`photo_url` AS `profile_photo_url`, `pp_profile`.`is_current` AS `profile_is_current`, `pp_cover`.`id` AS `cover_photo_id`, `pp_cover`.`photo_url` AS `cover_photo_url`, `pp_cover`.`is_current` AS `cover_is_current` FROM (((`users` `u` left join `user_profiles` `up` on(`u`.`id` = `up`.`user_id`)) left join `profile_photos` `pp_profile` on(`u`.`id` = `pp_profile`.`user_id` and `pp_profile`.`photo_type` = 'profile' and `pp_profile`.`is_current` = 1)) left join `profile_photos` `pp_cover` on(`u`.`id` = `pp_cover`.`user_id` and `pp_cover`.`photo_type` = 'cover' and `pp_cover`.`is_current` = 1)) ;

-- --------------------------------------------------------

--
-- Structure for view `v_user_statistics`
--
DROP TABLE IF EXISTS `v_user_statistics`;

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_user_statistics`  AS SELECT `u`.`id` AS `user_id`, `u`.`full_name` AS `full_name`, `u`.`user_type` AS `user_type`, count(distinct `f`.`id`) AS `total_farms`, count(distinct `e`.`id`) AS `total_enterprises`, count(distinct `p`.`id`) AS `total_products`, count(distinct case when `fr`.`status` = 'accepted' then `fr`.`id` end) AS `total_friends`, coalesce(avg(`r`.`rating`),0) AS `average_rating`, count(distinct `r`.`id`) AS `total_reviews` FROM (((((`users` `u` left join `farms` `f` on(`u`.`id` = `f`.`user_id`)) left join `enterprises` `e` on(`f`.`id` = `e`.`farm_id`)) left join `products` `p` on(`u`.`id` = `p`.`seller_id`)) left join `friendships` `fr` on(`u`.`id` = `fr`.`user_id` or `u`.`id` = `fr`.`friend_id`)) left join `reviews` `r` on(`u`.`id` = `r`.`reviewed_user_id`)) GROUP BY `u`.`id`, `u`.`full_name`, `u`.`user_type` ;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `activity_log`
--
ALTER TABLE `activity_log`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_date` (`user_id`,`created_at`),
  ADD KEY `idx_action` (`action`);

--
-- Indexes for table `admin_activity_log`
--
ALTER TABLE `admin_activity_log`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_admin` (`admin_id`),
  ADD KEY `idx_action` (`action_type`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_table_record` (`affected_table`,`affected_record_id`);

--
-- Indexes for table `admin_permissions`
--
ALTER TABLE `admin_permissions`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `permission_key` (`permission_key`),
  ADD KEY `idx_permission_key` (`permission_key`),
  ADD KEY `idx_category` (`permission_category`);

--
-- Indexes for table `admin_roles`
--
ALTER TABLE `admin_roles`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `role_name` (`role_name`),
  ADD KEY `idx_role_name` (`role_name`),
  ADD KEY `idx_role_level` (`role_level`);

--
-- Indexes for table `agricultural_tips`
--
ALTER TABLE `agricultural_tips`
  ADD PRIMARY KEY (`id`),
  ADD KEY `created_by` (`created_by`),
  ADD KEY `idx_category` (`category`),
  ADD KEY `idx_crop` (`crop_type`),
  ADD KEY `idx_language` (`language`),
  ADD KEY `idx_agricultural_tips_search` (`language`,`is_published`,`crop_type`,`title`(50),`content`(100));

--
-- Indexes for table `ai_conversations`
--
ALTER TABLE `ai_conversations`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_session` (`session_id`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_source` (`source`),
  ADD KEY `idx_user_language` (`user_id`,`language`),
  ADD KEY `idx_session_id` (`session_id`),
  ADD KEY `idx_user_sessions` (`user_id`,`session_id`,`created_at`);

--
-- Indexes for table `ai_conversation_feedback`
--
ALTER TABLE `ai_conversation_feedback`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_conversation` (`conversation_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_rating` (`rating`);

--
-- Indexes for table `ai_knowledge_sources`
--
ALTER TABLE `ai_knowledge_sources`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_type` (`source_type`),
  ADD KEY `idx_active` (`is_active`),
  ADD KEY `idx_priority` (`priority`);

--
-- Indexes for table `ai_learned_patterns`
--
ALTER TABLE `ai_learned_patterns`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_language` (`language`),
  ADD KEY `idx_active` (`is_active`),
  ADD KEY `idx_success` (`success_rate`),
  ADD KEY `idx_usage` (`usage_count`);

--
-- Indexes for table `ai_session_context`
--
ALTER TABLE `ai_session_context`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_session` (`session_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_updated` (`updated_at`);

--
-- Indexes for table `api_rate_limits`
--
ALTER TABLE `api_rate_limits`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_rate_limit` (`ip_address`,`endpoint`,`window_start`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_ip_endpoint` (`ip_address`,`endpoint`),
  ADD KEY `idx_blocked` (`is_blocked`);

--
-- Indexes for table `backup_restorations`
--
ALTER TABLE `backup_restorations`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_backup` (`backup_id`),
  ADD KEY `idx_restored_by` (`restored_by`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `bulk_orders`
--
ALTER TABLE `bulk_orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer_status` (`buyer_id`,`status`);

--
-- Indexes for table `bulk_order_bids`
--
ALTER TABLE `bulk_order_bids`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_bulk_order` (`bulk_order_id`),
  ADD KEY `idx_farmer` (`farmer_id`);

--
-- Indexes for table `buyer_payment_methods`
--
ALTER TABLE `buyer_payment_methods`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer` (`buyer_id`);

--
-- Indexes for table `buyer_preferences`
--
ALTER TABLE `buyer_preferences`
  ADD PRIMARY KEY (`id`),
  ADD KEY `buyer_id` (`buyer_id`);

--
-- Indexes for table `buyer_profiles`
--
ALTER TABLE `buyer_profiles`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_id` (`user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_type` (`buyer_type`),
  ADD KEY `idx_verified` (`is_verified`),
  ADD KEY `idx_district` (`business_district`);

--
-- Indexes for table `buyer_watchlist`
--
ALTER TABLE `buyer_watchlist`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer_active` (`buyer_id`,`is_active`);

--
-- Indexes for table `chats`
--
ALTER TABLE `chats`
  ADD PRIMARY KEY (`id`),
  ADD KEY `created_by` (`created_by`),
  ADD KEY `idx_type` (`chat_type`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_chat_type_updated` (`chat_type`,`updated_at`),
  ADD KEY `idx_type_updated` (`chat_type`,`updated_at`);

--
-- Indexes for table `chat_encryption_keys`
--
ALTER TABLE `chat_encryption_keys`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_chat_user` (`chat_id`,`user_id`),
  ADD KEY `idx_chat` (`chat_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `chat_members`
--
ALTER TABLE `chat_members`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_membership` (`chat_id`,`user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_chat` (`chat_id`),
  ADD KEY `idx_user_chat` (`user_id`,`chat_id`),
  ADD KEY `idx_chat_user` (`chat_id`,`user_id`),
  ADD KEY `idx_chat_members_chat_count` (`chat_id`);

--
-- Indexes for table `chat_member_audit`
--
ALTER TABLE `chat_member_audit`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `comment_likes`
--
ALTER TABLE `comment_likes`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_comment_like` (`comment_id`,`user_id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `contract_deliveries`
--
ALTER TABLE `contract_deliveries`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_contract` (`contract_id`);

--
-- Indexes for table `crop_diseases`
--
ALTER TABLE `crop_diseases`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_crop` (`crop_type`),
  ADD KEY `idx_category` (`category`),
  ADD KEY `idx_severity` (`severity_level`),
  ADD KEY `created_by` (`created_by`),
  ADD KEY `idx_crop_diseases_search` (`language`,`is_published`,`crop_type`,`disease_name`(50),`symptoms`(100));

--
-- Indexes for table `crop_varieties`
--
ALTER TABLE `crop_varieties`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_crop` (`crop_type`),
  ADD KEY `created_by` (`created_by`);

--
-- Indexes for table `database_backups`
--
ALTER TABLE `database_backups`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_type` (`backup_type`),
  ADD KEY `idx_status` (`backup_status`),
  ADD KEY `idx_created` (`created_by`),
  ADD KEY `idx_started` (`started_at`);

--
-- Indexes for table `disease_reports`
--
ALTER TABLE `disease_reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_disease` (`disease_id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `verified_by` (`verified_by`);

--
-- Indexes for table `districts`
--
ALTER TABLE `districts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_region` (`region_id`),
  ADD KEY `idx_name` (`district_name`);

--
-- Indexes for table `email_queue`
--
ALTER TABLE `email_queue`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_priority` (`priority`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `encrypted_files`
--
ALTER TABLE `encrypted_files`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_message` (`message_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `encryption_audit_log`
--
ALTER TABLE `encryption_audit_log`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_action` (`user_id`,`action_type`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `enterprises`
--
ALTER TABLE `enterprises`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_farm` (`farm_id`),
  ADD KEY `idx_type` (`enterprise_type`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `extension_activity_log`
--
ALTER TABLE `extension_activity_log`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_assignment` (`assignment_id`),
  ADD KEY `idx_date` (`activity_date`),
  ADD KEY `idx_type` (`activity_type`),
  ADD KEY `idx_date_type` (`activity_date`,`activity_type`);

--
-- Indexes for table `extension_assignments`
--
ALTER TABLE `extension_assignments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_role` (`role_id`),
  ADD KEY `idx_level` (`assigned_level`),
  ADD KEY `idx_location` (`region_id`,`district_id`,`subcounty_id`,`parish_id`,`village_id`),
  ADD KEY `idx_supervisor` (`supervisor_id`),
  ADD KEY `idx_active` (`is_active`),
  ADD KEY `extension_assignments_ibfk_4` (`assigned_by`),
  ADD KEY `idx_composite_location` (`assigned_level`,`region_id`,`district_id`,`subcounty_id`),
  ADD KEY `idx_ea_region` (`region_id`),
  ADD KEY `idx_ea_district` (`district_id`),
  ADD KEY `idx_ea_subcounty` (`subcounty_id`),
  ADD KEY `idx_ea_parish` (`parish_id`),
  ADD KEY `idx_ea_village` (`village_id`);

--
-- Indexes for table `extension_officer_profiles`
--
ALTER TABLE `extension_officer_profiles`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_id` (`user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_organization` (`organization`),
  ADD KEY `idx_verified` (`is_verified`);

--
-- Indexes for table `extension_reports`
--
ALTER TABLE `extension_reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_submitted_by` (`submitted_by`),
  ADD KEY `idx_assignment` (`assignment_id`),
  ADD KEY `idx_type` (`report_type`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_period` (`report_period_start`,`report_period_end`),
  ADD KEY `extension_reports_ibfk_3` (`reviewed_by`),
  ADD KEY `idx_period_status` (`report_period_start`,`report_period_end`,`status`);

--
-- Indexes for table `extension_resources`
--
ALTER TABLE `extension_resources`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_created_by` (`created_by`),
  ADD KEY `idx_type` (`resource_type`),
  ADD KEY `idx_level` (`target_level`),
  ADD KEY `idx_published` (`is_published`);

--
-- Indexes for table `extension_roles`
--
ALTER TABLE `extension_roles`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_role_level` (`role_name`,`role_level`),
  ADD KEY `idx_level` (`role_level`),
  ADD KEY `idx_org_type` (`organization_type`);

--
-- Indexes for table `extension_services`
--
ALTER TABLE `extension_services`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_officer` (`officer_id`),
  ADD KEY `idx_date` (`scheduled_date`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `extension_specializations`
--
ALTER TABLE `extension_specializations`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_assignment` (`assignment_id`),
  ADD KEY `idx_type` (`specialization_type`);

--
-- Indexes for table `failed_login_attempts`
--
ALTER TABLE `failed_login_attempts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_phone` (`phone_number`),
  ADD KEY `idx_ip` (`ip_address`),
  ADD KEY `idx_blocked` (`is_blocked`),
  ADD KEY `idx_last_attempt` (`last_attempt`);

--
-- Indexes for table `farming_contracts`
--
ALTER TABLE `farming_contracts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer` (`buyer_id`),
  ADD KEY `idx_farmer` (`farmer_id`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `farming_schedules`
--
ALTER TABLE `farming_schedules`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_crop` (`crop_type`),
  ADD KEY `idx_activity` (`activity_type`),
  ADD KEY `idx_timing` (`week_from_planting`),
  ADD KEY `created_by` (`created_by`),
  ADD KEY `idx_farming_schedules_search` (`language`,`is_published`,`crop_type`,`activity_type`,`week_from_planting`);

--
-- Indexes for table `farms`
--
ALTER TABLE `farms`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `favorites`
--
ALTER TABLE `favorites`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_favorite` (`user_id`,`product_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_product` (`product_id`);

--
-- Indexes for table `friendships`
--
ALTER TABLE `friendships`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_friendship` (`user_id`,`friend_id`),
  ADD KEY `idx_user_status` (`user_id`,`status`),
  ADD KEY `idx_friend` (`friend_id`);

--
-- Indexes for table `friend_suggestions`
--
ALTER TABLE `friend_suggestions`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_suggestion` (`user_id`,`suggested_user_id`),
  ADD KEY `suggested_user_id` (`suggested_user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_dismissed` (`is_dismissed`);

--
-- Indexes for table `groups`
--
ALTER TABLE `groups`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_created_by` (`created_by`),
  ADD KEY `idx_privacy` (`privacy`),
  ADD KEY `idx_category` (`category`);

--
-- Indexes for table `group_events`
--
ALTER TABLE `group_events`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_group` (`group_id`),
  ADD KEY `idx_date` (`event_date`),
  ADD KEY `created_by` (`created_by`);

--
-- Indexes for table `group_members`
--
ALTER TABLE `group_members`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_membership` (`group_id`,`user_id`),
  ADD KEY `idx_group` (`group_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `invited_by` (`invited_by`);

--
-- Indexes for table `group_posts`
--
ALTER TABLE `group_posts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_group_created` (`group_id`,`created_at`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_pinned` (`is_pinned`);

--
-- Indexes for table `group_post_comments`
--
ALTER TABLE `group_post_comments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_post` (`post_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_parent` (`parent_comment_id`);

--
-- Indexes for table `group_post_likes`
--
ALTER TABLE `group_post_likes`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_post_like` (`post_id`,`user_id`),
  ADD KEY `idx_post` (`post_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `ip_access_control`
--
ALTER TABLE `ip_access_control`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_ip_type` (`ip_address`,`access_type`),
  ADD KEY `idx_ip` (`ip_address`),
  ADD KEY `idx_type` (`access_type`),
  ADD KEY `idx_active` (`is_active`);

--
-- Indexes for table `learning_progress`
--
ALTER TABLE `learning_progress`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_user_content` (`user_id`,`content_type`,`content_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_type` (`content_type`);

--
-- Indexes for table `markets`
--
ALTER TABLE `markets`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `market_name` (`market_name`),
  ADD KEY `idx_location` (`location`),
  ADD KEY `idx_district` (`district`);

--
-- Indexes for table `market_prices`
--
ALTER TABLE `market_prices`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_product_date` (`product_type`,`price_date`),
  ADD KEY `idx_location` (`market_location`),
  ADD KEY `idx_date` (`price_date`),
  ADD KEY `idx_product_location_date` (`product_type`,`market_location`,`price_date`),
  ADD KEY `idx_source` (`source`);

--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_chat_date` (`chat_id`,`created_at`),
  ADD KEY `idx_sender` (`sender_id`),
  ADD KEY `idx_messages_chat_sender` (`chat_id`,`sender_id`),
  ADD KEY `idx_encrypted_messages` (`is_encrypted`,`chat_id`),
  ADD KEY `idx_message_hash` (`message_hash`),
  ADD KEY `idx_chat_created` (`chat_id`,`created_at`),
  ADD KEY `idx_receiver` (`receiver_id`),
  ADD KEY `idx_sender_receiver` (`sender_id`,`receiver_id`),
  ADD KEY `idx_chat_receiver_created` (`chat_id`,`receiver_id`,`created_at`),
  ADD KEY `idx_sender_created` (`sender_id`,`created_at`);

--
-- Indexes for table `message_attachments`
--
ALTER TABLE `message_attachments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_message` (`message_id`);

--
-- Indexes for table `message_reactions`
--
ALTER TABLE `message_reactions`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_reaction` (`message_id`,`user_id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `idx_message` (`message_id`);

--
-- Indexes for table `message_reports`
--
ALTER TABLE `message_reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_reporter` (`reporter_id`),
  ADD KEY `idx_message` (`message_id`);

--
-- Indexes for table `network_usage`
--
ALTER TABLE `network_usage`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_endpoint` (`endpoint`),
  ADD KEY `idx_recorded` (`recorded_at`),
  ADD KEY `idx_ip` (`ip_address`),
  ADD KEY `idx_network_usage_stats` (`recorded_at`,`endpoint`,`user_id`);

--
-- Indexes for table `notifications`
--
ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_read` (`user_id`,`is_read`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_notifications_user_read_created` (`user_id`,`is_read`,`created_at`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `order_number` (`order_number`),
  ADD KEY `product_id` (`product_id`),
  ADD KEY `idx_order_number` (`order_number`),
  ADD KEY `idx_buyer` (`buyer_id`),
  ADD KEY `idx_seller` (`seller_id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_orders_buyer_status` (`buyer_id`,`status`),
  ADD KEY `idx_orders_seller_status` (`seller_id`,`status`);

--
-- Indexes for table `otp_verifications`
--
ALTER TABLE `otp_verifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_phone_otp` (`phone_number`,`otp_code`),
  ADD KEY `idx_expires` (`expires_at`);

--
-- Indexes for table `parishes`
--
ALTER TABLE `parishes`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_subcounty` (`subcounty_id`),
  ADD KEY `idx_name` (`parish_name`);

--
-- Indexes for table `photo_comments`
--
ALTER TABLE `photo_comments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_photo` (`photo_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `photo_likes`
--
ALTER TABLE `photo_likes`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_photo_like` (`photo_id`,`user_id`),
  ADD KEY `idx_photo` (`photo_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_created` (`user_id`,`created_at`),
  ADD KEY `idx_visibility` (`visibility`),
  ADD KEY `idx_post_type` (`post_type`);

--
-- Indexes for table `post_comments`
--
ALTER TABLE `post_comments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_post` (`post_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_parent` (`parent_comment_id`);

--
-- Indexes for table `post_likes`
--
ALTER TABLE `post_likes`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_like` (`post_id`,`user_id`),
  ADD KEY `idx_post` (`post_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `price_alerts`
--
ALTER TABLE `price_alerts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_active` (`user_id`,`is_active`),
  ADD KEY `idx_product` (`product_type`);

--
-- Indexes for table `price_alert_notifications`
--
ALTER TABLE `price_alert_notifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_alert` (`alert_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_sent` (`notification_sent`);

--
-- Indexes for table `price_comparison_searches`
--
ALTER TABLE `price_comparison_searches`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_product` (`product_type`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `price_history`
--
ALTER TABLE `price_history`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_product_date` (`product_type`,`price_date`),
  ADD KEY `idx_location` (`market_location`),
  ADD KEY `idx_recorded` (`recorded_at`),
  ADD KEY `idx_history_product_date` (`product_type`,`price_date`),
  ADD KEY `idx_history_change` (`percent_change`);

--
-- Indexes for table `price_predictions`
--
ALTER TABLE `price_predictions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_product_date` (`product_type`,`prediction_date`),
  ADD KEY `idx_confidence` (`confidence_score`);

--
-- Indexes for table `price_reports`
--
ALTER TABLE `price_reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `verified_by` (`verified_by`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_product` (`product_type`),
  ADD KEY `idx_status` (`verification_status`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `price_sources`
--
ALTER TABLE `price_sources`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `source_name` (`source_name`),
  ADD KEY `idx_type` (`source_type`),
  ADD KEY `idx_active` (`is_active`);

--
-- Indexes for table `price_watchlist`
--
ALTER TABLE `price_watchlist`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_watchlist` (`user_id`,`product_type`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`),
  ADD KEY `enterprise_id` (`enterprise_id`),
  ADD KEY `idx_seller` (`seller_id`),
  ADD KEY `idx_category` (`category`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_products_category_status` (`category`,`status`);

--
-- Indexes for table `product_inquiries`
--
ALTER TABLE `product_inquiries`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_product` (`product_id`),
  ADD KEY `idx_buyer` (`buyer_id`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `profile_photos`
--
ALTER TABLE `profile_photos`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_type` (`user_id`,`photo_type`),
  ADD KEY `idx_current` (`is_current`),
  ADD KEY `idx_upload_date` (`upload_date`);

--
-- Indexes for table `profile_verifications`
--
ALTER TABLE `profile_verifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `verified_by` (`verified_by`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_type` (`verification_type`);

--
-- Indexes for table `profile_views`
--
ALTER TABLE `profile_views`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_profile` (`profile_user_id`),
  ADD KEY `idx_visitor` (`visitor_user_id`),
  ADD KEY `idx_date` (`viewed_at`);

--
-- Indexes for table `purchase_requests`
--
ALTER TABLE `purchase_requests`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer_status` (`buyer_id`,`status`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `push_queue`
--
ALTER TABLE `push_queue`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `status` (`status`),
  ADD KEY `created_at` (`created_at`);

--
-- Indexes for table `push_subscriptions`
--
ALTER TABLE `push_subscriptions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `is_active` (`is_active`),
  ADD KEY `idx_user_endpoint` (`user_id`,`endpoint`(100));

--
-- Indexes for table `quality_specifications`
--
ALTER TABLE `quality_specifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_buyer_product` (`buyer_id`,`product_type`);

--
-- Indexes for table `quote_responses`
--
ALTER TABLE `quote_responses`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_request` (`request_id`),
  ADD KEY `idx_seller` (`seller_id`);

--
-- Indexes for table `regions`
--
ALTER TABLE `regions`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `region_name` (`region_name`),
  ADD UNIQUE KEY `region_code` (`region_code`),
  ADD KEY `idx_name` (`region_name`);

--
-- Indexes for table `reports`
--
ALTER TABLE `reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_reporter` (`reporter_id`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `idx_type` (`report_type`);

--
-- Indexes for table `reviews`
--
ALTER TABLE `reviews`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `idx_reviewer` (`reviewer_id`),
  ADD KEY `idx_reviewed` (`reviewed_user_id`),
  ADD KEY `idx_rating` (`rating`);

--
-- Indexes for table `role_permissions`
--
ALTER TABLE `role_permissions`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_role_permission` (`role_id`,`permission_id`),
  ADD KEY `granted_by` (`granted_by`),
  ADD KEY `idx_role` (`role_id`),
  ADD KEY `idx_permission` (`permission_id`);

--
-- Indexes for table `scheduled_tasks`
--
ALTER TABLE `scheduled_tasks`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_task_name` (`task_name`),
  ADD KEY `idx_active` (`is_active`),
  ADD KEY `idx_next_run` (`next_run`);

--
-- Indexes for table `seasonal_calendar`
--
ALTER TABLE `seasonal_calendar`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_region` (`region`),
  ADD KEY `idx_season` (`season_type`);

--
-- Indexes for table `seasonal_price_patterns`
--
ALTER TABLE `seasonal_price_patterns`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_pattern` (`product_type`,`month`),
  ADD KEY `idx_product` (`product_type`),
  ADD KEY `idx_month` (`month`);

--
-- Indexes for table `security_threats`
--
ALTER TABLE `security_threats`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_threat_type` (`threat_type`),
  ADD KEY `idx_severity` (`severity`),
  ADD KEY `idx_ip` (`ip_address`),
  ADD KEY `idx_detected` (`detected_at`),
  ADD KEY `idx_resolved` (`is_resolved`),
  ADD KEY `idx_security_threats_unresolved` (`is_resolved`,`severity`,`detected_at`);

--
-- Indexes for table `server_metrics`
--
ALTER TABLE `server_metrics`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_metric_type` (`metric_type`),
  ADD KEY `idx_recorded` (`recorded_at`),
  ADD KEY `idx_critical` (`is_critical`),
  ADD KEY `idx_server_metrics_critical` (`is_critical`,`recorded_at`);

--
-- Indexes for table `service_participants`
--
ALTER TABLE `service_participants`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_participation` (`service_id`,`user_id`),
  ADD KEY `idx_service` (`service_id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `session_keys`
--
ALTER TABLE `session_keys`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_chat` (`chat_id`),
  ADD KEY `idx_expires` (`expires_at`);

--
-- Indexes for table `skill_endorsements`
--
ALTER TABLE `skill_endorsements`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_endorsement` (`user_id`,`skill_name`,`endorser_id`),
  ADD KEY `endorser_id` (`endorser_id`),
  ADD KEY `idx_user_skill` (`user_id`,`skill_name`);

--
-- Indexes for table `ssl_certificates`
--
ALTER TABLE `ssl_certificates`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_domain` (`domain_name`),
  ADD KEY `idx_expiry` (`expiry_date`),
  ADD KEY `idx_expiring_soon` (`is_expiring_soon`);

--
-- Indexes for table `story_views`
--
ALTER TABLE `story_views`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_view` (`story_id`,`viewer_id`),
  ADD KEY `viewer_id` (`viewer_id`);

--
-- Indexes for table `subcounties`
--
ALTER TABLE `subcounties`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_district` (`district_id`),
  ADD KEY `idx_name` (`subcounty_name`);

--
-- Indexes for table `supplier_ratings`
--
ALTER TABLE `supplier_ratings`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `idx_supplier` (`supplier_id`),
  ADD KEY `idx_buyer` (`buyer_id`);

--
-- Indexes for table `system_alerts`
--
ALTER TABLE `system_alerts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_type` (`alert_type`),
  ADD KEY `idx_severity` (`severity`),
  ADD KEY `idx_acknowledged` (`is_acknowledged`),
  ADD KEY `idx_resolved` (`is_resolved`),
  ADD KEY `idx_created` (`created_at`),
  ADD KEY `idx_system_alerts_pending` (`is_acknowledged`,`is_resolved`,`severity`);

--
-- Indexes for table `system_audit_log`
--
ALTER TABLE `system_audit_log`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_event` (`event_type`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_entity` (`entity_type`,`entity_id`),
  ADD KEY `idx_created` (`created_at`);

--
-- Indexes for table `system_settings`
--
ALTER TABLE `system_settings`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `setting_key` (`setting_key`),
  ADD KEY `idx_key` (`setting_key`);

--
-- Indexes for table `transactions`
--
ALTER TABLE `transactions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_date` (`user_id`,`transaction_date`),
  ADD KEY `idx_type` (`transaction_type`),
  ADD KEY `idx_enterprise` (`enterprise_id`),
  ADD KEY `idx_transactions_user_type_date` (`user_id`,`transaction_type`,`transaction_date`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `phone_number` (`phone_number`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `idx_phone` (`phone_number`),
  ADD KEY `idx_email` (`email`),
  ADD KEY `idx_user_type` (`user_type`),
  ADD KEY `idx_users_region` (`region_id`),
  ADD KEY `idx_users_district` (`district_id`),
  ADD KEY `idx_users_subcounty` (`subcounty_id`),
  ADD KEY `idx_users_parish` (`parish_id`),
  ADD KEY `idx_users_village` (`village_id`),
  ADD KEY `idx_users_approval` (`approval_status`),
  ADD KEY `idx_users_admin_role` (`admin_role_id`),
  ADD KEY `idx_users_last_activity` (`last_activity`);

--
-- Indexes for table `user_achievements`
--
ALTER TABLE `user_achievements`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_achievement` (`user_id`,`achievement_type`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_type` (`achievement_type`);

--
-- Indexes for table `user_approvals`
--
ALTER TABLE `user_approvals`
  ADD PRIMARY KEY (`id`),
  ADD KEY `approved_by` (`approved_by`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_status` (`approval_status`),
  ADD KEY `idx_type` (`user_type`);

--
-- Indexes for table `user_blocks`
--
ALTER TABLE `user_blocks`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_block` (`blocker_id`,`blocked_id`),
  ADD KEY `idx_blocker` (`blocker_id`),
  ADD KEY `idx_blocked` (`blocked_id`);

--
-- Indexes for table `user_certifications`
--
ALTER TABLE `user_certifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_expiry` (`expiry_date`);

--
-- Indexes for table `user_education`
--
ALTER TABLE `user_education`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`);

--
-- Indexes for table `user_encryption_keys`
--
ALTER TABLE `user_encryption_keys`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_id` (`user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_fingerprint` (`fingerprint`);

--
-- Indexes for table `user_experience`
--
ALTER TABLE `user_experience`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_current` (`is_current`);

--
-- Indexes for table `user_farming_reminders`
--
ALTER TABLE `user_farming_reminders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_date` (`user_id`,`reminder_date`),
  ADD KEY `idx_status` (`status`),
  ADD KEY `enterprise_id` (`enterprise_id`),
  ADD KEY `schedule_id` (`schedule_id`);

--
-- Indexes for table `user_life_events`
--
ALTER TABLE `user_life_events`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_date` (`user_id`,`event_date`),
  ADD KEY `idx_type` (`event_type`);

--
-- Indexes for table `user_preferences`
--
ALTER TABLE `user_preferences`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_id` (`user_id`);

--
-- Indexes for table `user_profiles`
--
ALTER TABLE `user_profiles`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_id` (`user_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_visibility` (`profile_visibility`),
  ADD KEY `idx_completeness` (`profile_completeness`);

--
-- Indexes for table `user_recommendations`
--
ALTER TABLE `user_recommendations`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_recommender` (`recommender_id`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `user_reports`
--
ALTER TABLE `user_reports`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_reporter` (`reporter_id`),
  ADD KEY `idx_reported` (`reported_user_id`),
  ADD KEY `idx_status` (`status`);

--
-- Indexes for table `user_saved_items`
--
ALTER TABLE `user_saved_items`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `unique_save` (`user_id`,`item_type`,`item_id`),
  ADD KEY `idx_user` (`user_id`),
  ADD KEY `idx_type` (`item_type`),
  ADD KEY `idx_collection` (`collection_name`);

--
-- Indexes for table `user_stories`
--
ALTER TABLE `user_stories`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_user_expires` (`user_id`,`expires_at`);

--
-- Indexes for table `villages`
--
ALTER TABLE `villages`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_parish` (`parish_id`),
  ADD KEY `idx_name` (`village_name`);

--
-- Indexes for table `weather_data`
--
ALTER TABLE `weather_data`
  ADD PRIMARY KEY (`id`),
  ADD KEY `idx_location_date` (`location`,`forecast_date`),
  ADD KEY `idx_forecast` (`is_forecast`,`forecast_date`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `activity_log`
--
ALTER TABLE `activity_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=104;

--
-- AUTO_INCREMENT for table `admin_activity_log`
--
ALTER TABLE `admin_activity_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;

--
-- AUTO_INCREMENT for table `admin_permissions`
--
ALTER TABLE `admin_permissions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;

--
-- AUTO_INCREMENT for table `admin_roles`
--
ALTER TABLE `admin_roles`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `agricultural_tips`
--
ALTER TABLE `agricultural_tips`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;

--
-- AUTO_INCREMENT for table `ai_conversations`
--
ALTER TABLE `ai_conversations`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48;

--
-- AUTO_INCREMENT for table `ai_conversation_feedback`
--
ALTER TABLE `ai_conversation_feedback`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `ai_knowledge_sources`
--
ALTER TABLE `ai_knowledge_sources`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;

--
-- AUTO_INCREMENT for table `ai_learned_patterns`
--
ALTER TABLE `ai_learned_patterns`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `ai_session_context`
--
ALTER TABLE `ai_session_context`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;

--
-- AUTO_INCREMENT for table `api_rate_limits`
--
ALTER TABLE `api_rate_limits`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `backup_restorations`
--
ALTER TABLE `backup_restorations`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `bulk_orders`
--
ALTER TABLE `bulk_orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `bulk_order_bids`
--
ALTER TABLE `bulk_order_bids`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `buyer_payment_methods`
--
ALTER TABLE `buyer_payment_methods`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `buyer_preferences`
--
ALTER TABLE `buyer_preferences`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `buyer_profiles`
--
ALTER TABLE `buyer_profiles`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `buyer_watchlist`
--
ALTER TABLE `buyer_watchlist`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `chats`
--
ALTER TABLE `chats`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `chat_encryption_keys`
--
ALTER TABLE `chat_encryption_keys`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `chat_members`
--
ALTER TABLE `chat_members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `chat_member_audit`
--
ALTER TABLE `chat_member_audit`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `comment_likes`
--
ALTER TABLE `comment_likes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `contract_deliveries`
--
ALTER TABLE `contract_deliveries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `crop_diseases`
--
ALTER TABLE `crop_diseases`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;

--
-- AUTO_INCREMENT for table `crop_varieties`
--
ALTER TABLE `crop_varieties`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;

--
-- AUTO_INCREMENT for table `database_backups`
--
ALTER TABLE `database_backups`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `disease_reports`
--
ALTER TABLE `disease_reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `districts`
--
ALTER TABLE `districts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=148;

--
-- AUTO_INCREMENT for table `email_queue`
--
ALTER TABLE `email_queue`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `encrypted_files`
--
ALTER TABLE `encrypted_files`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `encryption_audit_log`
--
ALTER TABLE `encryption_audit_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `enterprises`
--
ALTER TABLE `enterprises`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `extension_activity_log`
--
ALTER TABLE `extension_activity_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `extension_assignments`
--
ALTER TABLE `extension_assignments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `extension_officer_profiles`
--
ALTER TABLE `extension_officer_profiles`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `extension_reports`
--
ALTER TABLE `extension_reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `extension_resources`
--
ALTER TABLE `extension_resources`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `extension_roles`
--
ALTER TABLE `extension_roles`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `extension_services`
--
ALTER TABLE `extension_services`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `extension_specializations`
--
ALTER TABLE `extension_specializations`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `failed_login_attempts`
--
ALTER TABLE `failed_login_attempts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `farming_contracts`
--
ALTER TABLE `farming_contracts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `farming_schedules`
--
ALTER TABLE `farming_schedules`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;

--
-- AUTO_INCREMENT for table `farms`
--
ALTER TABLE `farms`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `favorites`
--
ALTER TABLE `favorites`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `friendships`
--
ALTER TABLE `friendships`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `friend_suggestions`
--
ALTER TABLE `friend_suggestions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `groups`
--
ALTER TABLE `groups`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `group_events`
--
ALTER TABLE `group_events`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `group_members`
--
ALTER TABLE `group_members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `group_posts`
--
ALTER TABLE `group_posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `group_post_comments`
--
ALTER TABLE `group_post_comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `group_post_likes`
--
ALTER TABLE `group_post_likes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `ip_access_control`
--
ALTER TABLE `ip_access_control`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `learning_progress`
--
ALTER TABLE `learning_progress`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for table `markets`
--
ALTER TABLE `markets`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `market_prices`
--
ALTER TABLE `market_prices`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=79;

--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

--
-- AUTO_INCREMENT for table `message_attachments`
--
ALTER TABLE `message_attachments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `message_reactions`
--
ALTER TABLE `message_reactions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `message_reports`
--
ALTER TABLE `message_reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `network_usage`
--
ALTER TABLE `network_usage`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `notifications`
--
ALTER TABLE `notifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;

--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `otp_verifications`
--
ALTER TABLE `otp_verifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `parishes`
--
ALTER TABLE `parishes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=162;

--
-- AUTO_INCREMENT for table `photo_comments`
--
ALTER TABLE `photo_comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `photo_likes`
--
ALTER TABLE `photo_likes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `post_comments`
--
ALTER TABLE `post_comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `post_likes`
--
ALTER TABLE `post_likes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `price_alerts`
--
ALTER TABLE `price_alerts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `price_alert_notifications`
--
ALTER TABLE `price_alert_notifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `price_comparison_searches`
--
ALTER TABLE `price_comparison_searches`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `price_history`
--
ALTER TABLE `price_history`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=68;

--
-- AUTO_INCREMENT for table `price_predictions`
--
ALTER TABLE `price_predictions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `price_reports`
--
ALTER TABLE `price_reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `price_sources`
--
ALTER TABLE `price_sources`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `price_watchlist`
--
ALTER TABLE `price_watchlist`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `product_inquiries`
--
ALTER TABLE `product_inquiries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `profile_photos`
--
ALTER TABLE `profile_photos`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `profile_verifications`
--
ALTER TABLE `profile_verifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `profile_views`
--
ALTER TABLE `profile_views`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `purchase_requests`
--
ALTER TABLE `purchase_requests`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `push_queue`
--
ALTER TABLE `push_queue`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

--
-- AUTO_INCREMENT for table `push_subscriptions`
--
ALTER TABLE `push_subscriptions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `quality_specifications`
--
ALTER TABLE `quality_specifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `quote_responses`
--
ALTER TABLE `quote_responses`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `regions`
--
ALTER TABLE `regions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

--
-- AUTO_INCREMENT for table `reports`
--
ALTER TABLE `reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `reviews`
--
ALTER TABLE `reviews`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `role_permissions`
--
ALTER TABLE `role_permissions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=118;

--
-- AUTO_INCREMENT for table `scheduled_tasks`
--
ALTER TABLE `scheduled_tasks`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `seasonal_calendar`
--
ALTER TABLE `seasonal_calendar`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `seasonal_price_patterns`
--
ALTER TABLE `seasonal_price_patterns`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `security_threats`
--
ALTER TABLE `security_threats`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `server_metrics`
--
ALTER TABLE `server_metrics`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `service_participants`
--
ALTER TABLE `service_participants`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `session_keys`
--
ALTER TABLE `session_keys`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `skill_endorsements`
--
ALTER TABLE `skill_endorsements`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `ssl_certificates`
--
ALTER TABLE `ssl_certificates`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `story_views`
--
ALTER TABLE `story_views`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `subcounties`
--
ALTER TABLE `subcounties`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=41;

--
-- AUTO_INCREMENT for table `supplier_ratings`
--
ALTER TABLE `supplier_ratings`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `system_alerts`
--
ALTER TABLE `system_alerts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `system_audit_log`
--
ALTER TABLE `system_audit_log`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `system_settings`
--
ALTER TABLE `system_settings`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

--
-- AUTO_INCREMENT for table `transactions`
--
ALTER TABLE `transactions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

--
-- AUTO_INCREMENT for table `user_achievements`
--
ALTER TABLE `user_achievements`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_approvals`
--
ALTER TABLE `user_approvals`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_blocks`
--
ALTER TABLE `user_blocks`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_certifications`
--
ALTER TABLE `user_certifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_education`
--
ALTER TABLE `user_education`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_encryption_keys`
--
ALTER TABLE `user_encryption_keys`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `user_experience`
--
ALTER TABLE `user_experience`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_farming_reminders`
--
ALTER TABLE `user_farming_reminders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_life_events`
--
ALTER TABLE `user_life_events`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_preferences`
--
ALTER TABLE `user_preferences`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_profiles`
--
ALTER TABLE `user_profiles`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `user_recommendations`
--
ALTER TABLE `user_recommendations`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_reports`
--
ALTER TABLE `user_reports`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_saved_items`
--
ALTER TABLE `user_saved_items`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `user_stories`
--
ALTER TABLE `user_stories`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `villages`
--
ALTER TABLE `villages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=802;

--
-- AUTO_INCREMENT for table `weather_data`
--
ALTER TABLE `weather_data`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `activity_log`
--
ALTER TABLE `activity_log`
  ADD CONSTRAINT `activity_log_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `admin_activity_log`
--
ALTER TABLE `admin_activity_log`
  ADD CONSTRAINT `admin_activity_log_ibfk_1` FOREIGN KEY (`admin_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `agricultural_tips`
--
ALTER TABLE `agricultural_tips`
  ADD CONSTRAINT `agricultural_tips_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `ai_conversations`
--
ALTER TABLE `ai_conversations`
  ADD CONSTRAINT `ai_conversations_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `ai_conversation_feedback`
--
ALTER TABLE `ai_conversation_feedback`
  ADD CONSTRAINT `ai_conversation_feedback_ibfk_1` FOREIGN KEY (`conversation_id`) REFERENCES `ai_conversations` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `ai_conversation_feedback_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `ai_session_context`
--
ALTER TABLE `ai_session_context`
  ADD CONSTRAINT `ai_session_context_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `bulk_orders`
--
ALTER TABLE `bulk_orders`
  ADD CONSTRAINT `bulk_orders_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `bulk_order_bids`
--
ALTER TABLE `bulk_order_bids`
  ADD CONSTRAINT `bulk_order_bids_ibfk_1` FOREIGN KEY (`bulk_order_id`) REFERENCES `bulk_orders` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `bulk_order_bids_ibfk_2` FOREIGN KEY (`farmer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `buyer_payment_methods`
--
ALTER TABLE `buyer_payment_methods`
  ADD CONSTRAINT `buyer_payment_methods_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `buyer_preferences`
--
ALTER TABLE `buyer_preferences`
  ADD CONSTRAINT `buyer_preferences_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `buyer_profiles`
--
ALTER TABLE `buyer_profiles`
  ADD CONSTRAINT `buyer_profiles_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `buyer_watchlist`
--
ALTER TABLE `buyer_watchlist`
  ADD CONSTRAINT `buyer_watchlist_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `chats`
--
ALTER TABLE `chats`
  ADD CONSTRAINT `chats_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `chat_encryption_keys`
--
ALTER TABLE `chat_encryption_keys`
  ADD CONSTRAINT `chat_encryption_keys_ibfk_1` FOREIGN KEY (`chat_id`) REFERENCES `chats` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `chat_encryption_keys_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `chat_members`
--
ALTER TABLE `chat_members`
  ADD CONSTRAINT `chat_members_ibfk_1` FOREIGN KEY (`chat_id`) REFERENCES `chats` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `chat_members_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `comment_likes`
--
ALTER TABLE `comment_likes`
  ADD CONSTRAINT `comment_likes_ibfk_1` FOREIGN KEY (`comment_id`) REFERENCES `post_comments` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `comment_likes_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `contract_deliveries`
--
ALTER TABLE `contract_deliveries`
  ADD CONSTRAINT `contract_deliveries_ibfk_1` FOREIGN KEY (`contract_id`) REFERENCES `farming_contracts` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `crop_diseases`
--
ALTER TABLE `crop_diseases`
  ADD CONSTRAINT `crop_diseases_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `crop_varieties`
--
ALTER TABLE `crop_varieties`
  ADD CONSTRAINT `crop_varieties_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `disease_reports`
--
ALTER TABLE `disease_reports`
  ADD CONSTRAINT `disease_reports_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `disease_reports_ibfk_2` FOREIGN KEY (`disease_id`) REFERENCES `crop_diseases` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `disease_reports_ibfk_3` FOREIGN KEY (`verified_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `districts`
--
ALTER TABLE `districts`
  ADD CONSTRAINT `districts_ibfk_1` FOREIGN KEY (`region_id`) REFERENCES `regions` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `encrypted_files`
--
ALTER TABLE `encrypted_files`
  ADD CONSTRAINT `encrypted_files_ibfk_1` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `encrypted_files_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `encryption_audit_log`
--
ALTER TABLE `encryption_audit_log`
  ADD CONSTRAINT `encryption_audit_log_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `enterprises`
--
ALTER TABLE `enterprises`
  ADD CONSTRAINT `enterprises_ibfk_1` FOREIGN KEY (`farm_id`) REFERENCES `farms` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `extension_activity_log`
--
ALTER TABLE `extension_activity_log`
  ADD CONSTRAINT `extension_activity_log_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `extension_activity_log_ibfk_2` FOREIGN KEY (`assignment_id`) REFERENCES `extension_assignments` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `extension_assignments`
--
ALTER TABLE `extension_assignments`
  ADD CONSTRAINT `extension_assignments_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `extension_assignments_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `extension_roles` (`id`),
  ADD CONSTRAINT `extension_assignments_ibfk_3` FOREIGN KEY (`supervisor_id`) REFERENCES `users` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `extension_assignments_ibfk_4` FOREIGN KEY (`assigned_by`) REFERENCES `users` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_ea_district` FOREIGN KEY (`district_id`) REFERENCES `districts` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_ea_parish` FOREIGN KEY (`parish_id`) REFERENCES `parishes` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_ea_region` FOREIGN KEY (`region_id`) REFERENCES `regions` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_ea_subcounty` FOREIGN KEY (`subcounty_id`) REFERENCES `subcounties` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_ea_village` FOREIGN KEY (`village_id`) REFERENCES `villages` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `extension_officer_profiles`
--
ALTER TABLE `extension_officer_profiles`
  ADD CONSTRAINT `extension_officer_profiles_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `extension_reports`
--
ALTER TABLE `extension_reports`
  ADD CONSTRAINT `extension_reports_ibfk_1` FOREIGN KEY (`submitted_by`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `extension_reports_ibfk_2` FOREIGN KEY (`assignment_id`) REFERENCES `extension_assignments` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `extension_reports_ibfk_3` FOREIGN KEY (`reviewed_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `extension_resources`
--
ALTER TABLE `extension_resources`
  ADD CONSTRAINT `extension_resources_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `extension_services`
--
ALTER TABLE `extension_services`
  ADD CONSTRAINT `extension_services_ibfk_1` FOREIGN KEY (`officer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `extension_specializations`
--
ALTER TABLE `extension_specializations`
  ADD CONSTRAINT `extension_specializations_ibfk_1` FOREIGN KEY (`assignment_id`) REFERENCES `extension_assignments` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `farming_contracts`
--
ALTER TABLE `farming_contracts`
  ADD CONSTRAINT `farming_contracts_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `farming_contracts_ibfk_2` FOREIGN KEY (`farmer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `farming_schedules`
--
ALTER TABLE `farming_schedules`
  ADD CONSTRAINT `farming_schedules_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `farms`
--
ALTER TABLE `farms`
  ADD CONSTRAINT `farms_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `favorites`
--
ALTER TABLE `favorites`
  ADD CONSTRAINT `favorites_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `favorites_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `friendships`
--
ALTER TABLE `friendships`
  ADD CONSTRAINT `friendships_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `friendships_ibfk_2` FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `friend_suggestions`
--
ALTER TABLE `friend_suggestions`
  ADD CONSTRAINT `friend_suggestions_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `friend_suggestions_ibfk_2` FOREIGN KEY (`suggested_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `groups`
--
ALTER TABLE `groups`
  ADD CONSTRAINT `groups_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `group_events`
--
ALTER TABLE `group_events`
  ADD CONSTRAINT `group_events_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_events_ibfk_2` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `group_members`
--
ALTER TABLE `group_members`
  ADD CONSTRAINT `group_members_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_members_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_members_ibfk_3` FOREIGN KEY (`invited_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `group_posts`
--
ALTER TABLE `group_posts`
  ADD CONSTRAINT `group_posts_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_posts_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `group_post_comments`
--
ALTER TABLE `group_post_comments`
  ADD CONSTRAINT `group_post_comments_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `group_posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_post_comments_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_post_comments_ibfk_3` FOREIGN KEY (`parent_comment_id`) REFERENCES `group_post_comments` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `group_post_likes`
--
ALTER TABLE `group_post_likes`
  ADD CONSTRAINT `group_post_likes_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `group_posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `group_post_likes_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `learning_progress`
--
ALTER TABLE `learning_progress`
  ADD CONSTRAINT `learning_progress_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `messages`
--
ALTER TABLE `messages`
  ADD CONSTRAINT `messages_ibfk_1` FOREIGN KEY (`chat_id`) REFERENCES `chats` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `messages_ibfk_2` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `message_attachments`
--
ALTER TABLE `message_attachments`
  ADD CONSTRAINT `message_attachments_ibfk_1` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `message_reactions`
--
ALTER TABLE `message_reactions`
  ADD CONSTRAINT `message_reactions_ibfk_1` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `message_reactions_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `notifications`
--
ALTER TABLE `notifications`
  ADD CONSTRAINT `notifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`),
  ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`),
  ADD CONSTRAINT `orders_ibfk_3` FOREIGN KEY (`seller_id`) REFERENCES `users` (`id`);

--
-- Constraints for table `parishes`
--
ALTER TABLE `parishes`
  ADD CONSTRAINT `parishes_ibfk_1` FOREIGN KEY (`subcounty_id`) REFERENCES `subcounties` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `photo_comments`
--
ALTER TABLE `photo_comments`
  ADD CONSTRAINT `photo_comments_ibfk_1` FOREIGN KEY (`photo_id`) REFERENCES `profile_photos` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `photo_comments_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `photo_likes`
--
ALTER TABLE `photo_likes`
  ADD CONSTRAINT `photo_likes_ibfk_1` FOREIGN KEY (`photo_id`) REFERENCES `profile_photos` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `photo_likes_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `posts`
--
ALTER TABLE `posts`
  ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `post_comments`
--
ALTER TABLE `post_comments`
  ADD CONSTRAINT `post_comments_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `post_comments_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `post_comments_ibfk_3` FOREIGN KEY (`parent_comment_id`) REFERENCES `post_comments` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `post_likes`
--
ALTER TABLE `post_likes`
  ADD CONSTRAINT `post_likes_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `post_likes_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `price_alerts`
--
ALTER TABLE `price_alerts`
  ADD CONSTRAINT `price_alerts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `price_alert_notifications`
--
ALTER TABLE `price_alert_notifications`
  ADD CONSTRAINT `price_alert_notifications_ibfk_1` FOREIGN KEY (`alert_id`) REFERENCES `price_alerts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `price_alert_notifications_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `price_comparison_searches`
--
ALTER TABLE `price_comparison_searches`
  ADD CONSTRAINT `price_comparison_searches_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `price_reports`
--
ALTER TABLE `price_reports`
  ADD CONSTRAINT `price_reports_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `price_reports_ibfk_2` FOREIGN KEY (`verified_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `price_watchlist`
--
ALTER TABLE `price_watchlist`
  ADD CONSTRAINT `price_watchlist_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `products`
--
ALTER TABLE `products`
  ADD CONSTRAINT `products_ibfk_1` FOREIGN KEY (`seller_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `products_ibfk_2` FOREIGN KEY (`enterprise_id`) REFERENCES `enterprises` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `product_inquiries`
--
ALTER TABLE `product_inquiries`
  ADD CONSTRAINT `product_inquiries_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `product_inquiries_ibfk_2` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `profile_photos`
--
ALTER TABLE `profile_photos`
  ADD CONSTRAINT `profile_photos_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `profile_verifications`
--
ALTER TABLE `profile_verifications`
  ADD CONSTRAINT `profile_verifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `profile_verifications_ibfk_2` FOREIGN KEY (`verified_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `profile_views`
--
ALTER TABLE `profile_views`
  ADD CONSTRAINT `profile_views_ibfk_1` FOREIGN KEY (`profile_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `profile_views_ibfk_2` FOREIGN KEY (`visitor_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `purchase_requests`
--
ALTER TABLE `purchase_requests`
  ADD CONSTRAINT `purchase_requests_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `push_queue`
--
ALTER TABLE `push_queue`
  ADD CONSTRAINT `push_queue_user_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `push_subscriptions`
--
ALTER TABLE `push_subscriptions`
  ADD CONSTRAINT `push_subscriptions_user_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `quality_specifications`
--
ALTER TABLE `quality_specifications`
  ADD CONSTRAINT `quality_specifications_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `quote_responses`
--
ALTER TABLE `quote_responses`
  ADD CONSTRAINT `quote_responses_ibfk_1` FOREIGN KEY (`request_id`) REFERENCES `purchase_requests` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `quote_responses_ibfk_2` FOREIGN KEY (`seller_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `reports`
--
ALTER TABLE `reports`
  ADD CONSTRAINT `reports_ibfk_1` FOREIGN KEY (`reporter_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `reviews`
--
ALTER TABLE `reviews`
  ADD CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`reviewer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `reviews_ibfk_2` FOREIGN KEY (`reviewed_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `reviews_ibfk_3` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `role_permissions`
--
ALTER TABLE `role_permissions`
  ADD CONSTRAINT `role_permissions_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `admin_roles` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `role_permissions_ibfk_2` FOREIGN KEY (`permission_id`) REFERENCES `admin_permissions` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `role_permissions_ibfk_3` FOREIGN KEY (`granted_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `service_participants`
--
ALTER TABLE `service_participants`
  ADD CONSTRAINT `service_participants_ibfk_1` FOREIGN KEY (`service_id`) REFERENCES `extension_services` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `service_participants_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `session_keys`
--
ALTER TABLE `session_keys`
  ADD CONSTRAINT `session_keys_ibfk_1` FOREIGN KEY (`chat_id`) REFERENCES `chats` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `skill_endorsements`
--
ALTER TABLE `skill_endorsements`
  ADD CONSTRAINT `skill_endorsements_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `skill_endorsements_ibfk_2` FOREIGN KEY (`endorser_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `story_views`
--
ALTER TABLE `story_views`
  ADD CONSTRAINT `story_views_ibfk_1` FOREIGN KEY (`story_id`) REFERENCES `user_stories` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `story_views_ibfk_2` FOREIGN KEY (`viewer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `subcounties`
--
ALTER TABLE `subcounties`
  ADD CONSTRAINT `subcounties_ibfk_1` FOREIGN KEY (`district_id`) REFERENCES `districts` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `supplier_ratings`
--
ALTER TABLE `supplier_ratings`
  ADD CONSTRAINT `supplier_ratings_ibfk_1` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `supplier_ratings_ibfk_2` FOREIGN KEY (`supplier_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `supplier_ratings_ibfk_3` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `system_audit_log`
--
ALTER TABLE `system_audit_log`
  ADD CONSTRAINT `system_audit_log_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `transactions`
--
ALTER TABLE `transactions`
  ADD CONSTRAINT `transactions_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `transactions_ibfk_2` FOREIGN KEY (`enterprise_id`) REFERENCES `enterprises` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `users`
--
ALTER TABLE `users`
  ADD CONSTRAINT `fk_users_district` FOREIGN KEY (`district_id`) REFERENCES `districts` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_users_parish` FOREIGN KEY (`parish_id`) REFERENCES `parishes` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_users_region` FOREIGN KEY (`region_id`) REFERENCES `regions` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_users_subcounty` FOREIGN KEY (`subcounty_id`) REFERENCES `subcounties` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `fk_users_village` FOREIGN KEY (`village_id`) REFERENCES `villages` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`admin_role_id`) REFERENCES `admin_roles` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `user_achievements`
--
ALTER TABLE `user_achievements`
  ADD CONSTRAINT `user_achievements_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_approvals`
--
ALTER TABLE `user_approvals`
  ADD CONSTRAINT `user_approvals_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `user_approvals_ibfk_2` FOREIGN KEY (`approved_by`) REFERENCES `users` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `user_blocks`
--
ALTER TABLE `user_blocks`
  ADD CONSTRAINT `user_blocks_ibfk_1` FOREIGN KEY (`blocker_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `user_blocks_ibfk_2` FOREIGN KEY (`blocked_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_certifications`
--
ALTER TABLE `user_certifications`
  ADD CONSTRAINT `user_certifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_education`
--
ALTER TABLE `user_education`
  ADD CONSTRAINT `user_education_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_encryption_keys`
--
ALTER TABLE `user_encryption_keys`
  ADD CONSTRAINT `user_encryption_keys_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_experience`
--
ALTER TABLE `user_experience`
  ADD CONSTRAINT `user_experience_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_farming_reminders`
--
ALTER TABLE `user_farming_reminders`
  ADD CONSTRAINT `user_farming_reminders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `user_farming_reminders_ibfk_2` FOREIGN KEY (`enterprise_id`) REFERENCES `enterprises` (`id`) ON DELETE SET NULL,
  ADD CONSTRAINT `user_farming_reminders_ibfk_3` FOREIGN KEY (`schedule_id`) REFERENCES `farming_schedules` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `user_life_events`
--
ALTER TABLE `user_life_events`
  ADD CONSTRAINT `user_life_events_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_preferences`
--
ALTER TABLE `user_preferences`
  ADD CONSTRAINT `user_preferences_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_profiles`
--
ALTER TABLE `user_profiles`
  ADD CONSTRAINT `user_profiles_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_recommendations`
--
ALTER TABLE `user_recommendations`
  ADD CONSTRAINT `user_recommendations_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `user_recommendations_ibfk_2` FOREIGN KEY (`recommender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_saved_items`
--
ALTER TABLE `user_saved_items`
  ADD CONSTRAINT `user_saved_items_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `user_stories`
--
ALTER TABLE `user_stories`
  ADD CONSTRAINT `user_stories_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `villages`
--
ALTER TABLE `villages`
  ADD CONSTRAINT `villages_ibfk_1` FOREIGN KEY (`parish_id`) REFERENCES `parishes` (`id`) ON DELETE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
