<?php
session_start();
require 'config.php';

header('Content-Type: application/json');

// Debug: Log session info
error_log("Admin Feedback API - Session admin_id: " . (isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 'NOT SET'));

// Check if user is admin - check for admin_id which is always set by login
// if (!isset($_SESSION['admin_id']) || empty($_SESSION['admin_id'])) {
//     http_response_code(401);
//     echo json_encode([
//         'success' => false,
//         'message' => 'Unauthorized access - Admin not logged in'
//     ]);
//     exit;
// }

$method = $_SERVER['REQUEST_METHOD'];

// Handle new_count action first
if ($method === 'GET' && isset($_GET['action']) && $_GET['action'] === 'new_count') {
    // Get count of new feedback
    try {
        $sql = "SELECT COUNT(*) as count FROM feedback WHERE status = 'pending'";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();
        
        echo json_encode([
            'success' => true,
            'count' => (int)$row['count']
        ]);
        exit;
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
        exit;
    }
}

if ($method === 'GET') {
    // Fetch all feedback for admin with username
    try {
        $sql = "SELECT f.id, f.user_id, u.name as username, f.subject, f.message, f.rating, f.status, f.created_at 
                FROM feedback f
                LEFT JOIN users u ON f.user_id = u.id
                ORDER BY f.created_at DESC";
        
        $result = $conn->query($sql);
        
        if ($result) {
            $feedback = [];
            while ($row = $result->fetch_assoc()) {
                $feedback[] = $row;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $feedback,
                'count' => count($feedback)
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Database error: ' . $conn->error
            ]);
        }
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
} elseif ($method === 'POST') {
    // Handle POST for update_status action
    if (isset($_GET['action']) && $_GET['action'] === 'update_status') {
        try {
            $input = json_decode(file_get_contents('php://input'), true);
            $feedback_id = isset($input['feedback_id']) ? intval($input['feedback_id']) : 0;
            $new_status = isset($input['status']) ? trim($input['status']) : '';
            
            if (!$feedback_id || !in_array($new_status, ['pending', 'approved', 'rejected', 'read'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Invalid feedback ID or status'
                ]);
                exit;
            }
            
            $sql = "UPDATE feedback SET status = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $new_status, $feedback_id);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Feedback status updated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to update status: ' . $stmt->error
                ]);
            }
            $stmt->close();
            exit;
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
            exit;
        }
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}

$conn->close();
?>
