<?php
/**
 * Alert Service
 * Handles notifications for land changes, satellite alerts, neighbor confirmations, etc.
 */

class AlertService {

    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }

    /**
     * Send alert to a specific user
     */
    public function sendToUser($userId, $type, $title, $message, $landId = null, $data = []) {
        $userId = intval($userId);
        $type = mysqli_real_escape_string($this->conn, $type);
        $title = mysqli_real_escape_string($this->conn, $title);
        $message = mysqli_real_escape_string($this->conn, $message);
        $landIdSql = $landId ? intval($landId) : 'NULL';
        $metadata = !empty($data) ? mysqli_real_escape_string($this->conn, json_encode($data)) : 'NULL';

        $sql = "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                VALUES ($userId, '$type', '$title', '$message', $landIdSql, " . ($metadata === 'NULL' ? 'NULL' : "'$metadata'") . ", NOW())";

        return mysqli_query($this->conn, $sql);
    }

    /**
     * Send alert to multiple users
     */
    public function sendToUsers($userIds, $type, $title, $message, $landId = null, $data = []) {
        $count = 0;
        foreach ($userIds as $userId) {
            if ($this->sendToUser($userId, $type, $title, $message, $landId, $data)) {
                $count++;
            }
        }
        return $count;
    }

    /**
     * Send alert to all users in a village
     */
    public function sendToVillage($villageId, $type, $title, $message, $landId = null, $excludeUserId = null, $data = []) {
        $villageId = intval($villageId);

        $excludeClause = $excludeUserId ? "AND id != " . intval($excludeUserId) : "";

        $result = mysqli_query($this->conn, "
            SELECT id FROM users
            WHERE village_id = $villageId AND status = 'active' $excludeClause
        ");

        $userIds = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $userIds[] = $row['id'];
        }

        return $this->sendToUsers($userIds, $type, $title, $message, $landId, $data);
    }

    /**
     * Send alert to village officials only
     */
    public function sendToVillageOfficials($villageId, $type, $title, $message, $landId = null, $data = []) {
        $villageId = intval($villageId);

        $result = mysqli_query($this->conn, "
            SELECT id FROM users
            WHERE village_id = $villageId
            AND role IN ('village_chairman', 'land_officer', 'surveyor', 'land_council')
            AND status = 'active'
        ");

        $userIds = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $userIds[] = $row['id'];
        }

        return $this->sendToUsers($userIds, $type, $title, $message, $landId, $data);
    }

    /**
     * Send alert to land neighbors
     */
    public function sendToNeighbors($landId, $type, $title, $message, $excludeUserId = null, $data = []) {
        $landId = intval($landId);
        $excludeClause = $excludeUserId ? "AND ln.neighbor_user_id != " . intval($excludeUserId) : "";

        $result = mysqli_query($this->conn, "
            SELECT DISTINCT ln.neighbor_user_id
            FROM land_neighbors ln
            WHERE ln.land_id = $landId
            AND ln.neighbor_user_id IS NOT NULL
            $excludeClause
        ");

        $userIds = [];
        while ($row = mysqli_fetch_assoc($result)) {
            if ($row['neighbor_user_id']) {
                $userIds[] = $row['neighbor_user_id'];
            }
        }

        return $this->sendToUsers($userIds, $type, $title, $message, $landId, $data);
    }

    /**
     * Alert: New land registered in village
     */
    public function alertNewLandRegistered($landId, $villageId, $ownerId) {
        $land = $this->getLandInfo($landId);
        if (!$land) return 0;

        $title = "Ardhi Mpya Imesajiliwa / New Land Registered";
        $message = "A new land \"{$land['land_name']}\" has been registered in your village by {$land['owner_name']}. ";
        $message .= "Location: {$land['village_name']}.";

        // Alert village officials
        $count = $this->sendToVillageOfficials($villageId, 'new_land', $title, $message, $landId, [
            'land_name' => $land['land_name'],
            'owner_name' => $land['owner_name'],
            'area' => $land['area_size']
        ]);

        return $count;
    }

    /**
     * Alert: Satellite change detected
     */
    public function alertSatelliteChange($landId, $changeType, $severity, $changeData = []) {
        $land = $this->getLandInfo($landId);
        if (!$land) return 0;

        $changeLabel = $this->getChangeTypeLabel($changeType);
        $severityLabel = $this->getSeverityLabel($severity);

        // Alert to land owner
        $ownerTitle = "Tahadhari: Mabadiliko Yamegunduliwa / Alert: Change Detected";
        $ownerMessage = "Satellite monitoring has detected a {$changeLabel} on your land \"{$land['land_name']}\". ";
        $ownerMessage .= "Severity: {$severityLabel}. Please review this change.";

        $this->sendToUser($land['user_id'], 'satellite_alert', $ownerTitle, $ownerMessage, $landId, [
            'change_type' => $changeType,
            'severity' => $severity,
            'confidence' => $changeData['confidence_score'] ?? null
        ]);

        // Alert to neighbors
        $neighborTitle = "Mabadiliko Karibu na Ardhi Yako / Change Near Your Land";
        $neighborMessage = "A {$changeLabel} has been detected on a neighboring land \"{$land['land_name']}\". ";
        $neighborMessage .= "This may affect your boundaries.";

        $this->sendToNeighbors($landId, 'neighbor_change', $neighborTitle, $neighborMessage, $land['user_id'], [
            'change_type' => $changeType,
            'severity' => $severity
        ]);

        // Alert village officials for high/critical severity
        if (in_array($severity, ['high', 'critical'])) {
            $officialTitle = "Tahadhari ya Dharura / Urgent Alert: Land Change";
            $officialMessage = "A {$severityLabel} {$changeLabel} has been detected on land \"{$land['land_name']}\" ";
            $officialMessage .= "owned by {$land['owner_name']}. Immediate review may be required.";

            $this->sendToVillageOfficials($land['village_id'], 'satellite_alert_official', $officialTitle, $officialMessage, $landId, [
                'change_type' => $changeType,
                'severity' => $severity,
                'owner_name' => $land['owner_name'],
                'owner_phone' => $land['owner_phone']
            ]);
        }

        return true;
    }

    /**
     * Alert: Neighbor confirmation requested
     */
    public function alertNeighborConfirmationNeeded($landId, $neighborUserId, $neighborName, $direction) {
        $land = $this->getLandInfo($landId);
        if (!$land) return false;

        $title = "Ombi la Uthibitisho wa Mpaka / Boundary Confirmation Request";
        $message = "You have been identified as a neighbor ({$direction}) for land \"{$land['land_name']}\" ";
        $message .= "owned by {$land['owner_name']}. Please confirm or dispute the boundary.";

        return $this->sendToUser($neighborUserId, 'neighbor_confirmation', $title, $message, $landId, [
            'direction' => $direction,
            'owner_name' => $land['owner_name'],
            'owner_phone' => $land['owner_phone']
        ]);
    }

    /**
     * Alert: Neighbor confirmed boundary
     */
    public function alertNeighborConfirmed($landId, $neighborName, $direction) {
        $land = $this->getLandInfo($landId);
        if (!$land) return false;

        $title = "Jirani Amethibitisha Mpaka / Neighbor Confirmed Boundary";
        $message = "Your neighbor {$neighborName} ({$direction} boundary) has confirmed the boundary for your land \"{$land['land_name']}\".";

        return $this->sendToUser($land['user_id'], 'neighbor_confirmed', $title, $message, $landId, [
            'neighbor_name' => $neighborName,
            'direction' => $direction
        ]);
    }

    /**
     * Alert: Neighbor disputed boundary
     */
    public function alertNeighborDisputed($landId, $neighborName, $direction, $reason) {
        $land = $this->getLandInfo($landId);
        if (!$land) return 0;

        // Alert land owner
        $ownerTitle = "Tahadhari: Mpaka Umepingwa / Alert: Boundary Disputed";
        $ownerMessage = "Your neighbor {$neighborName} ({$direction} boundary) has disputed the boundary for your land \"{$land['land_name']}\". ";
        $ownerMessage .= "Reason: {$reason}";

        $this->sendToUser($land['user_id'], 'neighbor_disputed', $ownerTitle, $ownerMessage, $landId, [
            'neighbor_name' => $neighborName,
            'direction' => $direction,
            'reason' => $reason
        ]);

        // Alert village officials
        $officialTitle = "Mgogoro wa Mpaka Umeripotiwa / Boundary Dispute Reported";
        $officialMessage = "A boundary dispute has been raised for land \"{$land['land_name']}\" by neighbor {$neighborName}. ";
        $officialMessage .= "Please investigate.";

        $this->sendToVillageOfficials($land['village_id'], 'dispute_raised', $officialTitle, $officialMessage, $landId, [
            'neighbor_name' => $neighborName,
            'direction' => $direction,
            'reason' => $reason,
            'owner_name' => $land['owner_name']
        ]);

        return true;
    }

    /**
     * Alert: Land verification status changed
     */
    public function alertVerificationStatusChanged($landId, $newStatus, $notes = '') {
        $land = $this->getLandInfo($landId);
        if (!$land) return false;

        $statusLabels = [
            'pending' => 'Inasubiri / Pending',
            'pending_village' => 'Inasubiri Kijiji / Pending Village',
            'village_approved' => 'Imeidhinishwa na Kijiji / Village Approved',
            'village_rejected' => 'Imekataliwa na Kijiji / Village Rejected',
            'pending_survey' => 'Inasubiri Upimaji / Pending Survey',
            'surveyor_verified' => 'Imethibitishwa na Mpima / Surveyor Verified',
            'fully_verified' => 'Imethibitishwa Kikamilifu / Fully Verified'
        ];

        $statusLabel = $statusLabels[$newStatus] ?? ucfirst($newStatus);

        $title = "Hali ya Ardhi Imebadilika / Land Status Changed";
        $message = "Your land \"{$land['land_name']}\" status has changed to: {$statusLabel}.";
        if ($notes) {
            $message .= " Notes: {$notes}";
        }

        return $this->sendToUser($land['user_id'], 'status_change', $title, $message, $landId, [
            'new_status' => $newStatus,
            'notes' => $notes
        ]);
    }

    /**
     * Alert: Overlap detected with another land
     */
    public function alertOverlapDetected($landId, $overlappingLandId, $overlapPercentage) {
        $land = $this->getLandInfo($landId);
        $overlappingLand = $this->getLandInfo($overlappingLandId);

        if (!$land || !$overlappingLand) return 0;

        // Alert first land owner
        $title1 = "Tahadhari: Mgongano wa Mipaka / Alert: Boundary Overlap";
        $message1 = "Your land \"{$land['land_name']}\" overlaps with land \"{$overlappingLand['land_name']}\" ";
        $message1 .= "owned by {$overlappingLand['owner_name']}. Overlap: {$overlapPercentage}%";

        $this->sendToUser($land['user_id'], 'overlap_detected', $title1, $message1, $landId, [
            'overlapping_land_id' => $overlappingLandId,
            'overlapping_land_name' => $overlappingLand['land_name'],
            'overlap_percentage' => $overlapPercentage
        ]);

        // Alert second land owner
        $title2 = "Tahadhari: Mgongano wa Mipaka / Alert: Boundary Overlap";
        $message2 = "Your land \"{$overlappingLand['land_name']}\" overlaps with land \"{$land['land_name']}\" ";
        $message2 .= "owned by {$land['owner_name']}. Overlap: {$overlapPercentage}%";

        $this->sendToUser($overlappingLand['user_id'], 'overlap_detected', $title2, $message2, $overlappingLandId, [
            'overlapping_land_id' => $landId,
            'overlapping_land_name' => $land['land_name'],
            'overlap_percentage' => $overlapPercentage
        ]);

        // Alert village officials
        $officialTitle = "Mgongano wa Ardhi Umegunduliwa / Land Overlap Detected";
        $officialMessage = "An overlap ({$overlapPercentage}%) has been detected between land \"{$land['land_name']}\" ";
        $officialMessage .= "and \"{$overlappingLand['land_name']}\". Investigation required.";

        $this->sendToVillageOfficials($land['village_id'], 'overlap_official', $officialTitle, $officialMessage, $landId, [
            'land1_name' => $land['land_name'],
            'land1_owner' => $land['owner_name'],
            'land2_name' => $overlappingLand['land_name'],
            'land2_owner' => $overlappingLand['owner_name'],
            'overlap_percentage' => $overlapPercentage
        ]);

        return true;
    }

    /**
     * Alert: Payment received
     */
    public function alertPaymentReceived($userId, $amount, $paymentType, $reference) {
        $title = "Malipo Yamepokelewa / Payment Received";
        $message = "Your payment of TZS " . number_format($amount) . " for {$paymentType} has been received. ";
        $message .= "Reference: {$reference}";

        return $this->sendToUser($userId, 'payment_received', $title, $message, null, [
            'amount' => $amount,
            'payment_type' => $paymentType,
            'reference' => $reference
        ]);
    }

    /**
     * Alert: Certificate issued
     */
    public function alertCertificateIssued($landId, $certificateNumber) {
        $land = $this->getLandInfo($landId);
        if (!$land) return false;

        $title = "Cheti Kimetolewa / Certificate Issued";
        $message = "Congratulations! A digital certificate has been issued for your land \"{$land['land_name']}\". ";
        $message .= "Certificate Number: {$certificateNumber}";

        return $this->sendToUser($land['user_id'], 'certificate_issued', $title, $message, $landId, [
            'certificate_number' => $certificateNumber
        ]);
    }

    /**
     * Get land info helper
     */
    private function getLandInfo($landId) {
        $landId = intval($landId);

        $result = mysqli_query($this->conn, "
            SELECT l.*, u.full_name as owner_name, u.phone as owner_phone, u.email as owner_email,
                   v.name as village_name
            FROM lands l
            JOIN users u ON l.user_id = u.id
            LEFT JOIN villages v ON l.village_id = v.id
            WHERE l.id = $landId
        ");

        return mysqli_fetch_assoc($result);
    }

    /**
     * Get unread notification count for a user
     */
    public function getUnreadCount($userId) {
        $userId = intval($userId);

        $result = mysqli_query($this->conn, "
            SELECT COUNT(*) as count FROM cbc_notifications
            WHERE user_id = $userId AND is_read = 0
        ");

        $row = mysqli_fetch_assoc($result);
        return $row['count'] ?? 0;
    }

    /**
     * Get notifications for a user
     */
    public function getNotifications($userId, $limit = 20, $unreadOnly = false) {
        $userId = intval($userId);
        $limit = intval($limit);
        $unreadClause = $unreadOnly ? "AND is_read = 0" : "";

        $result = mysqli_query($this->conn, "
            SELECT n.*, l.land_name
            FROM cbc_notifications n
            LEFT JOIN lands l ON n.land_id = l.id
            WHERE n.user_id = $userId $unreadClause
            ORDER BY n.created_at DESC
            LIMIT $limit
        ");

        $notifications = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $notifications[] = $row;
        }

        return $notifications;
    }

    /**
     * Mark notification as read
     */
    public function markAsRead($notificationId, $userId) {
        $notificationId = intval($notificationId);
        $userId = intval($userId);

        return mysqli_query($this->conn, "
            UPDATE cbc_notifications SET is_read = 1, read_at = NOW()
            WHERE id = $notificationId AND user_id = $userId
        ");
    }

    /**
     * Mark all notifications as read
     */
    public function markAllAsRead($userId) {
        $userId = intval($userId);

        return mysqli_query($this->conn, "
            UPDATE cbc_notifications SET is_read = 1, read_at = NOW()
            WHERE user_id = $userId AND is_read = 0
        ");
    }

    /**
     * Get change type labels
     */
    private function getChangeTypeLabel($type) {
        $labels = [
            'vegetation_loss' => 'Vegetation Loss / Kupotea kwa Mimea',
            'vegetation_gain' => 'Vegetation Growth / Kuongezeka kwa Mimea',
            'new_structure' => 'New Structure / Jengo Jipya',
            'land_clearing' => 'Land Clearing / Kusafisha Ardhi',
            'water_change' => 'Water Change / Mabadiliko ya Maji',
            'soil_disturbance' => 'Soil Disturbance / Kuchimbwa kwa Ardhi',
            'boundary_encroachment' => 'Boundary Encroachment / Uvamizi wa Mpaka',
            'fire_damage' => 'Fire Damage / Uharibifu wa Moto',
            'flooding' => 'Flooding / Mafuriko',
            'erosion' => 'Erosion / Mmomonyoko'
        ];

        return $labels[$type] ?? $type;
    }

    /**
     * Get severity labels
     */
    private function getSeverityLabel($severity) {
        $labels = [
            'low' => 'Low / Chini',
            'medium' => 'Medium / Wastani',
            'high' => 'High / Juu',
            'critical' => 'Critical / Hatari'
        ];

        return $labels[$severity] ?? $severity;
    }
}
