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

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

// Debug: Log session info
error_log("Admin Contacts 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 contact messages
    try {
        $sql = "SELECT COUNT(*) as count FROM contacts WHERE status = 'new' OR status = 'unread'";
        $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 contact messages for admin
    try {
        $sql = "SELECT id, name, email, phone, subject, message, status, created_at 
                FROM contacts ORDER BY created_at DESC";
        
        $result = $conn->query($sql);
        
        if ($result) {
            $contacts = [];
            while ($row = $result->fetch_assoc()) {
                $contacts[] = $row;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $contacts,
                'count' => count($contacts)
            ]);
        } 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') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['action']) || !isset($input['contact_id'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Missing required parameters'
            ]);
            exit;
        }
        
        $action = $input['action'];
        $contact_id = (int)$input['contact_id'];
        
        if ($action === 'delete') {
            // Delete contact
            $sql = "DELETE FROM contacts WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $contact_id);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Contact deleted successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error deleting contact: ' . $stmt->error
                ]);
            }
            $stmt->close();
        } elseif ($action === 'read') {
            // Mark as read
            $sql = "UPDATE contacts SET status = 'read' WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $contact_id);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Contact marked as read'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error updating contact: ' . $stmt->error
                ]);
            }
            $stmt->close();
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Unknown action'
            ]);
        }
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}

$conn->close();
?>
