<?php
/**
 * Client - Feedbacks (Submit/View)
 * SSCI Office Platform - Feedback Submission
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Check authentication
if (!$auth->isAuthenticated() || $_SESSION['role'] !== 'client') {
    header('Location: ?page=login');
    exit();
}

// Get guards assigned to user's posts
$guards = $db->fetchAll(
    "SELECT DISTINCT u.id, u.name, u.phone, u.email
     FROM users u
     JOIN guard_post_assignments gpa ON u.id = gpa.guard_id
     JOIN posts p ON gpa.post_id = p.id
     WHERE p.owner_id = ? AND u.role = 'guard'
     ORDER BY u.name",
    [$_SESSION['user_id']]
);

// Get feedback history for user
$feedbacks = $db->fetchAll(
    "SELECT * FROM feedback
     WHERE Client = ?
     ORDER BY Date DESC
     LIMIT 30",
    [$_SESSION['user_id']]
);

require_once __DIR__ . '/../layouts/header.php';
?>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl pb-20 md:pb-8">
    <!-- Page Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between mb-2">
            <div>
                <h1 class="text-3xl sm:text-4xl font-bold text-gray-900">
                    <i class="fas fa-star text-amber-400 mr-3"></i>Performance Feedback
                </h1>
                <p class="text-gray-600 text-base mt-2">Rate guard performance and view submitted feedback</p>
            </div>
        </div>
        <div class="h-1 w-20 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full mt-4"></div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Feedback Form -->
        <div class="lg:col-span-1">
            <div class="bg-gradient-to-br from-white to-blue-50 rounded-xl shadow-lg border border-blue-100 p-6 sticky top-20">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-900">
                        <i class="fas fa-pen-to-square text-blue-600 mr-2"></i>New Feedback
                    </h2>
                    <span class="text-xs font-semibold px-3 py-1 bg-blue-100 text-blue-700 rounded-full">Required</span>
                </div>

                <form id="feedbackForm" onsubmit="submitFeedback(event)" class="space-y-5">
                    <!-- Guard Selection (Required) -->
                    <div>
                        <label class="block text-sm font-bold text-gray-800 mb-2">
                            <i class="fas fa-user-shield text-blue-600 mr-2"></i>Select Guard *
                        </label>
                        <select id="guardId" required onchange="updateSubject()" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-sm font-medium transition">
                            <option value="">Choose a guard...</option>
                            <?php foreach ($guards as $guard): ?>
                                <option value="<?php echo $guard['id']; ?>" data-name="<?php echo htmlspecialchars($guard['name']); ?>"><?php echo htmlspecialchars($guard['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- Date (Required) -->
                    <div>
                        <label class="block text-sm font-bold text-gray-800 mb-2">
                            <i class="fas fa-calendar text-green-600 mr-2"></i>Date *
                        </label>
                        <input type="date" id="feedbackDate" required onchange="updateSubject()" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-sm font-medium transition">
                    </div>

                    <!-- Subject (Auto-generated) -->
                    <div>
                        <label class="block text-sm font-bold text-gray-800 mb-2">
                            <i class="fas fa-heading text-purple-600 mr-2"></i>Subject
                        </label>
                        <input type="text" id="subject" readonly class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-100 text-sm font-medium text-gray-700" placeholder="Auto-generated">
                        <p class="text-xs text-gray-600 mt-1">Auto-generated from date and guard selection</p>
                    </div>



                    <!-- Live Score Display -->
                    <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 border border-blue-200 space-y-2">
                        <p class="text-xs font-bold text-gray-700 mb-3">
                            <i class="fas fa-chart-pie text-blue-600 mr-2"></i>Live Scores
                        </p>
                        <div class="grid grid-cols-2 gap-2 text-xs">
                            <div class="bg-white p-2 rounded border border-blue-100">
                                <div class="text-gray-600 font-semibold">Guard</div>
                                <div class="text-lg font-bold text-blue-600" id="guardScoreBadge">—</div>
                                <div class="text-gray-500 text-xs mt-1" id="guardScoreBar"></div>
                            </div>
                            <div class="bg-white p-2 rounded border border-green-100">
                                <div class="text-gray-600 font-semibold">Controller</div>
                                <div class="text-lg font-bold text-green-600" id="controllerScoreBadge">—</div>
                                <div class="text-gray-500 text-xs mt-1" id="controllerScoreBar"></div>
                            </div>
                            <div class="bg-white p-2 rounded border border-purple-100">
                                <div class="text-gray-600 font-semibold">Management</div>
                                <div class="text-lg font-bold text-purple-600" id="managementScoreBadge">—</div>
                                <div class="text-gray-500 text-xs mt-1" id="managementScoreBar"></div>
                            </div>
                            <div class="bg-white p-2 rounded border border-amber-100">
                                <div class="text-gray-600 font-semibold">Overall</div>
                                <div class="text-lg font-bold text-amber-600" id="overallScoreBadge">—</div>
                                <div class="text-gray-500 text-xs mt-1" id="overallScoreBar"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Guard Criteria (8 fields) - BLUE -->
                    <div class="border-t border-blue-200 pt-5 mt-5">
                        <p class="text-sm font-bold text-blue-700 mb-4 flex items-center gap-2">
                            <i class="fas fa-shield-alt text-blue-600"></i>Guard Performance (8 criteria)
                        </p>
                        
                        <div class="space-y-3">
                            <?php $guard_fields = ['Punctuality', 'Attendance', 'Neatness', 'Patrolling', 'Communication', 'Respect', 'Job_Mastery' => 'Job Mastery', 'Vigilance']; ?>
                            <?php foreach (['Punctuality', 'Attendance', 'Neatness', 'Patrolling', 'Communication', 'Respect', 'Job_Mastery', 'Vigilance'] as $field): ?>
                                <div class="flex items-center justify-between gap-3 p-2 rounded hover:bg-blue-50 transition">
                                    <label class="text-xs font-semibold text-gray-800 flex-1">
                                        <?php echo str_replace('_', ' ', $field); ?>
                                    </label>
                                    <div class="flex gap-1">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-sm cursor-pointer text-gray-300 hover:text-yellow-400 transition hover:scale-110" onclick="setRating('<?php echo $field; ?>', <?php echo $i; ?>)" id="<?php echo $field; ?>_<?php echo $i; ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Controller Criteria (3 fields) - GREEN -->
                    <div class="border-t border-green-200 pt-5 mt-5">
                        <p class="text-sm font-bold text-green-700 mb-4 flex items-center gap-2">
                            <i class="fas fa-users text-green-600"></i>Controller Ratings (3 criteria)
                        </p>
                        
                        <div class="space-y-3">
                            <?php foreach (['Frequency', 'Response', 'Collaboration'] as $field): ?>
                                <div class="flex items-center justify-between gap-3 p-2 rounded hover:bg-green-50 transition">
                                    <label class="text-xs font-semibold text-gray-800 flex-1">
                                        <?php echo str_replace('_', ' ', $field); ?>
                                    </label>
                                    <div class="flex gap-1">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-sm cursor-pointer text-gray-300 hover:text-yellow-400 transition hover:scale-110" onclick="setRating('<?php echo $field; ?>', <?php echo $i; ?>)" id="<?php echo $field; ?>_<?php echo $i; ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Management Criteria (4 fields) - PURPLE -->
                    <div class="border-t border-purple-200 pt-5 mt-5">
                        <p class="text-sm font-bold text-purple-700 mb-4 flex items-center gap-2">
                            <i class="fas fa-briefcase text-purple-600"></i>Management Ratings (4 criteria)
                        </p>
                        
                        <div class="space-y-3">
                            <?php foreach (['Service_Delivery' => 'Service Delivery', 'Timeliness', 'Innovation', 'Documentation'] as $dbField => $displayName): ?>
                                <?php $field = is_int($dbField) ? $displayName : $dbField; $display = is_int($dbField) ? $displayName : $displayName; ?>
                                <div class="flex items-center justify-between gap-3 p-2 rounded hover:bg-purple-50 transition">
                                    <label class="text-xs font-semibold text-gray-800 flex-1">
                                        <?php echo is_int($dbField) ? $displayName : str_replace('_', ' ', $dbField); ?>
                                    </label>
                                    <div class="flex gap-1">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-sm cursor-pointer text-gray-300 hover:text-yellow-400 transition hover:scale-110" onclick="setRating('<?php echo is_int($dbField) ? $displayName : $dbField; ?>', <?php echo $i; ?>)" id="<?php echo is_int($dbField) ? str_replace(' ', '_', $displayName) : $dbField; ?>_<?php echo $i; ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Additional Ratings (1 field) - ORANGE -->
                    <div class="border-t border-orange-200 pt-5 mt-5">
                        <p class="text-sm font-bold text-orange-700 mb-4 flex items-center gap-2">
                            <i class="fas fa-plus-circle text-orange-600"></i>Additional Rating
                        </p>
                        
                        <div class="flex items-center justify-between gap-3 p-2 rounded hover:bg-orange-50 transition">
                            <label class="text-xs font-semibold text-gray-800 flex-1">
                                Equipping
                            </label>
                            <div class="flex gap-1">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i class="fas fa-star text-sm cursor-pointer text-gray-300 hover:text-yellow-400 transition hover:scale-110" onclick="setRating('Equipping', <?php echo $i; ?>)" id="Equipping_<?php echo $i; ?>"></i>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Remarks -->
                    <div class="border-t border-gray-200 pt-5 mt-5">
                        <label class="block text-sm font-bold text-gray-800 mb-2">
                            <i class="fas fa-comment text-indigo-600 mr-2"></i>Remarks (Optional)
                        </label>
                        <textarea id="remarks" rows="4" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 text-sm font-medium transition resize-none" placeholder="Additional comments or observations..."></textarea>
                        <p class="text-xs text-gray-600 mt-1"><i class="fas fa-info-circle mr-1"></i>Share any additional context about the feedback</p>
                    </div>

                    <!-- Submit Button -->
                    <button type="submit" class="w-full px-4 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:shadow-lg font-bold transition-all flex items-center justify-center gap-2 mt-6">
                        <i class="fas fa-paper-plane"></i>Submit Feedback
                    </button>
                </form>
            </div>
        </div>

        <!-- Feedback History & Management -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-lg border border-gray-100">
                <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
                    <h2 class="text-xl font-bold text-gray-900">
                        <i class="fas fa-history text-indigo-600 mr-2"></i>Feedback History
                    </h2>
                    <p class="text-xs text-gray-600 mt-1">Manage your submitted feedback</p>
                </div>

                <?php if (!empty($feedbacks)): ?>
                    <div class="divide-y divide-gray-200 max-h-[600px] overflow-y-auto">
                        <?php foreach ($feedbacks as $feedback): ?>
                            <?php 
                                $guardScore = ((intval($feedback['Punctuality'] ?? 3) + intval($feedback['Attendance'] ?? 3) + intval($feedback['Neatness'] ?? 3) + intval($feedback['Patrolling'] ?? 3) + intval($feedback['Communication'] ?? 3) + intval($feedback['Respect'] ?? 3) + intval($feedback['Job_Mastery'] ?? 3) + intval($feedback['Vigilance'] ?? 3)) / 8);
                                $controllerScore = ((intval($feedback['Frequency'] ?? 3) + intval($feedback['Response'] ?? 3) + intval($feedback['Collaboration'] ?? 3)) / 3);
                                $managementScore = ((intval($feedback['Service_Delivery'] ?? 3) + intval($feedback['Timeliness'] ?? 3) + intval($feedback['Innovation'] ?? 3) + intval($feedback['Documentation'] ?? 3)) / 4);
                                $overallScore = floatval($feedback['Overall_Score'] ?? 3.0);
                            ?>
                            <div class="px-6 py-5 hover:bg-gradient-to-r hover:from-blue-50 hover:to-indigo-50 transition group">
                                <div class="flex items-start justify-between gap-4 mb-3">
                                    <div class="flex-1">
                                        <p class="font-bold text-gray-900 text-base group-hover:text-blue-700 transition"><?php echo htmlspecialchars($feedback['Subject'] ?? 'N/A'); ?></p>
                                        <div class="flex items-center gap-3 mt-2 flex-wrap">
                                            <span class="text-xs text-gray-600">
                                                <i class="fas fa-calendar-alt mr-1"></i><?php echo date('M d, Y', strtotime($feedback['Date'] ?? 'now')); ?>
                                            </span>
                                        </div>
                                    </div>
                                    
                                    <div class="text-right flex gap-2">
                                        <!-- Overall Score Badge -->
                                        <div class="text-center">
                                            <div class="text-xs font-bold text-gray-600">Overall</div>
                                            <div class="text-2xl font-bold text-amber-500"><?php echo number_format($overallScore, 2); ?></div>
                                            <div class="text-xs text-gray-500">/5.0</div>
                                        </div>

                                        <!-- Delete Button -->
                                        <button onclick="deleteFeedback(<?php echo $feedback['FeedID']; ?>)" class="px-3 py-2 text-red-600 hover:bg-red-50 rounded transition text-sm" title="Delete feedback">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                
                                <?php if (!empty($feedback['Remarks'])): ?>
                                    <p class="text-gray-700 text-sm mb-3 pl-0 border-l-4 border-indigo-300 pl-3"><?php echo htmlspecialchars($feedback['Remarks']); ?></p>
                                <?php endif; ?>
                                
                                <!-- Category Badges -->
                                <div class="grid grid-cols-4 gap-2 pt-3 border-t border-gray-100">
                                    <div class="text-center p-2 bg-blue-50 rounded text-xs">
                                        <div class="text-gray-600 font-bold">Guard</div>
                                        <div class="text-lg font-bold text-blue-600"><?php echo number_format($guardScore, 1); ?></div>
                                    </div>
                                    <div class="text-center p-2 bg-green-50 rounded text-xs">
                                        <div class="text-gray-600 font-bold">Controller</div>
                                        <div class="text-lg font-bold text-green-600"><?php echo number_format($controllerScore, 1); ?></div>
                                    </div>
                                    <div class="text-center p-2 bg-purple-50 rounded text-xs">
                                        <div class="text-gray-600 font-bold">Management</div>
                                        <div class="text-lg font-bold text-purple-600"><?php echo number_format($managementScore, 1); ?></div>
                                    </div>
                                    <div class="text-center p-2 bg-orange-50 rounded text-xs">
                                        <div class="text-gray-600 font-bold">Equipping</div>
                                        <div class="text-lg font-bold text-orange-600"><?php echo intval($feedback['Equipping'] ?? 3); ?></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="p-12 text-center text-gray-500">
                        <i class="fas fa-inbox text-5xl mb-4 opacity-20"></i>
                        <p class="text-base font-semibold">No feedback submitted yet</p>
                        <p class="text-sm mt-2">Start by submitting your first feedback on the left</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
const ratingValues = {};

// All rating fields from database schema
const ratingFields = [
    'Punctuality', 'Attendance', 'Neatness', 'Patrolling', 'Communication', 'Respect', 'Job_Mastery', 'Vigilance',  // Guard (8)
    'Frequency', 'Response', 'Collaboration',  // Controller (3)
    'Service_Delivery', 'Timeliness', 'Innovation', 'Documentation',  // Management (4)
    'Equipping'  // Additional (1)
];

const guardFields = ['Punctuality', 'Attendance', 'Neatness', 'Patrolling', 'Communication', 'Respect', 'Job_Mastery', 'Vigilance'];
const controllerFields = ['Frequency', 'Response', 'Collaboration'];
const managementFields = ['Service_Delivery', 'Timeliness', 'Innovation', 'Documentation'];

// Initialize rating values
ratingFields.forEach(field => {
    ratingValues[field] = 0;
});

function setRating(fieldId, value) {
    ratingValues[fieldId] = value;
    
    // Update star colors
    for (let i = 1; i <= 5; i++) {
        const star = document.getElementById(fieldId + '_' + i);
        if (star) {
            if (i <= value) {
                star.classList.remove('text-gray-300');
                star.classList.add('text-yellow-400');
            } else {
                star.classList.remove('text-yellow-400');
                star.classList.add('text-gray-300');
            }
        }
    }
    
    // Update live scores
    updateLiveScores();
}

function updateLiveScores() {
    // Calculate Guard Score
    const guardValues = guardFields.map(f => ratingValues[f] || 0).filter(v => v > 0);
    const guardScore = guardValues.length > 0 ? (guardValues.reduce((a, b) => a + b) / guardValues.length) : 0;

    // Calculate Controller Score
    const controllerValues = controllerFields.map(f => ratingValues[f] || 0).filter(v => v > 0);
    const controllerScore = controllerValues.length > 0 ? (controllerValues.reduce((a, b) => a + b) / controllerValues.length) : 0;

    // Calculate Management Score
    const managementValues = managementFields.map(f => ratingValues[f] || 0).filter(v => v > 0);
    const managementScore = managementValues.length > 0 ? (managementValues.reduce((a, b) => a + b) / managementValues.length) : 0;

    // Calculate Overall Score (50% Guard, 30% Controller, 20% Management + 5% Equipping)
    const equipping = ratingValues['Equipping'] || 0;
    const overallScore = guardScore > 0 ? (guardScore * 0.5) + (controllerScore * 0.3) + (managementScore * 0.2) : 0;

    // Update display
    document.getElementById('guardScoreBadge').textContent = guardScore > 0 ? guardScore.toFixed(2) : '—';
    document.getElementById('controllerScoreBadge').textContent = controllerScore > 0 ? controllerScore.toFixed(2) : '—';
    document.getElementById('managementScoreBadge').textContent = managementScore > 0 ? managementScore.toFixed(2) : '—';
    document.getElementById('overallScoreBadge').textContent = overallScore > 0 ? overallScore.toFixed(2) : '—';

    // Update score bars (progress visual)
    updateScoreBar('guardScoreBar', guardScore);
    updateScoreBar('controllerScoreBar', controllerScore);
    updateScoreBar('managementScoreBar', managementScore);
    updateScoreBar('overallScoreBar', overallScore);
}

function updateScoreBar(elementId, score) {
    const percentage = (score / 5) * 100;
    const bar = document.getElementById(elementId);
    if (bar) {
        const width = Math.round(percentage);
        bar.style.width = width + '%';
        bar.className = `h-1 bg-gradient-to-r from-blue-400 to-indigo-600 rounded-full transition-all`;
    }
}

function updateSubject() {
    const guardSelect = document.getElementById('guardId');
    const dateInput = document.getElementById('feedbackDate');
    const subjectInput = document.getElementById('subject');
    
    const guardName = guardSelect.options[guardSelect.selectedIndex]?.getAttribute('data-name') || '';
    const date = new Date(dateInput.value);
    const monthYear = date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
    
    if (guardName && monthYear && dateInput.value) {
        subjectInput.value = `Feedback for ${monthYear}`;
    } else {
        subjectInput.value = '';
    }
}

function submitFeedback(event) {
    event.preventDefault();
    
    const guardId = document.getElementById('guardId').value;
    const feedbackDate = document.getElementById('feedbackDate').value;
    const subject = document.getElementById('subject').value;
    const remarks = document.getElementById('remarks').value;

    if (!guardId || !feedbackDate || !subject) {
        showToast('Please fill in all required fields', 'warning');
        return;
    }

    // Build data payload with all rating fields
    const data = {
        subject: subject,
        guard_id: guardId,
        date: feedbackDate,
        remarks: remarks
    };

    // Add all rating fields
    ratingFields.forEach(field => {
        data[field] = parseInt(ratingValues[field]) || 3;  // Default to 3 if not set
    });

    fetch('?page=api&endpoint=clients/add-feedback', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(result => {
        if (result.success) {
            showToast('Feedback submitted successfully!', 'success');
            document.getElementById('feedbackForm').reset();
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast(result.error || result.message || 'Failed to submit feedback', 'error');
            console.error('API Response:', result);
        }
    })
    .catch(err => {
        console.error('Error:', err);
        showToast('An error occurred', 'error');
    });
}

function deleteFeedback(feedbackId) {
    if (!confirm('Are you sure you want to delete this feedback? This action cannot be undone.')) {
        return;
    }

    fetch('?page=api&endpoint=clients/delete-feedback&id=' + feedbackId, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(result => {
        if (result.success) {
            showToast('Feedback deleted successfully', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(result.error || 'Failed to delete feedback', 'error');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        showToast('An error occurred', 'error');
    });
}

// Set today's date as default on page load
window.addEventListener('load', () => {
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('feedbackDate').value = today;
    updateSubject();
});

// Update subject when date or guard changes
document.getElementById('feedbackDate')?.addEventListener('change', updateSubject);
document.getElementById('guardId')?.addEventListener('change', updateSubject);
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>
