<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class NotificationController {
    
    public function index() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE receiver_type = 'customer' AND receiver_id = ?");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT * FROM notifications 
            WHERE receiver_type = 'customer' AND receiver_id = ? 
            ORDER BY created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $notifications = $stmt->fetchAll();
        
        // Enrich notifications for the UI
        foreach ($notifications as &$n) {
            $n['is_read'] = intval($n['is_read']) === 1;
            
            // Format relative time (e.g. "2h ago", "Yesterday", "2 days ago")
            $time = strtotime($n['created_at']);
            $diff = time() - $time;
            if ($diff < 60) {
                $n['time_ago'] = 'Just now';
            } elseif ($diff < 3600) {
                $n['time_ago'] = round($diff / 60) . 'm ago';
            } elseif ($diff < 86400) {
                $n['time_ago'] = round($diff / 3600) . 'h ago';
            } elseif ($diff < 172800) {
                $n['time_ago'] = 'Yesterday';
            } else {
                $n['time_ago'] = round($diff / 86400) . ' days ago';
            }
            
            // Group notifications (TODAY vs EARLIER)
            $today = strtotime('today');
            if ($time >= $today) {
                $n['date_group'] = 'TODAY';
            } else {
                $n['date_group'] = 'EARLIER';
            }
            
            // Assign icon names based on notification type
            switch ($n['type']) {
                case 'interview_confirmed':
                    $n['icon'] = 'success';
                    break;
                case 'meeting_ready':
                    $n['icon'] = 'video';
                    break;
                case 'calendar_invite':
                    $n['icon'] = 'calendar';
                    break;
                case 'payment_processed':
                    $n['icon'] = 'payment';
                    break;
                case 'profile_updated':
                    $n['icon'] = 'profile';
                    break;
                default:
                    $n['icon'] = 'bell';
                    break;
            }
            
            // Define action buttons matching UI design
            $n['actions'] = [];
            if ($n['type'] === 'meeting_ready') {
                $n['actions'][] = [
                    'label' => 'Join Meeting',
                    'action' => 'join_meeting',
                    'style' => 'primary',
                    'url' => 'https://helperlink.com/meeting/join/' . ($n['related_id'] ?? $n['id'])
                ];
                $n['actions'][] = [
                    'label' => 'Details',
                    'action' => 'view_details',
                    'style' => 'secondary',
                    'url' => 'https://helperlink.com/interviews/' . ($n['related_id'] ?? $n['id'])
                ];
            } elseif ($n['type'] === 'profile_updated') {
                $n['actions'][] = [
                    'label' => 'Confirm Change',
                    'action' => 'confirm_change',
                    'style' => 'primary',
                    'url' => 'https://helperlink.com/profile/confirm/' . ($n['related_id'] ?? $n['id'])
                ];
            }
        }
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Notifications loaded successfully', ['notifications' => $notifications], $pagination);
    }
    
    public function read($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Verify notification belongs to customer
        $stmt = $db->prepare("SELECT id FROM notifications WHERE id = ? AND receiver_type = 'customer' AND receiver_id = ?");
        $stmt->execute([$id, $customerId]);
        if (!$stmt->fetch()) {
            sendError('Notification not found', [], 404);
        }
        
        $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE id = ?");
        $stmt->execute([$id]);
        
        sendResponse([], 'Notification marked as read');
    }
    
    public function readAll() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE receiver_type = 'customer' AND receiver_id = ?");
        $stmt->execute([$customerId]);
        
        sendResponse([], 'All notifications marked as read');
    }
}
