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

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

// 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') {
    try {
        // Users table doesn't have status field, so just return 0
        echo json_encode([
            'success' => true,
            'count' => 0
        ]);
        exit;
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
        exit;
    }
}

if ($method === 'GET') {
    // Fetch all users for admin
    try {
        $sql = "SELECT id, name, email, phone, created_at 
                FROM users ORDER BY created_at DESC";
        
        $result = $conn->query($sql);
        
        
        if ($result) {
            $users = [];
            while ($row = $result->fetch_assoc()) {
                $users[] = $row;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $users,
                'count' => count($users)
            ]);
        } 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'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Action is required'
            ]);
            exit;
        }
        
        $action = $input['action'];
        
        if ($action === 'edit') {
            // Validate required fields
            if (!isset($input['user_id']) || !isset($input['name']) || !isset($input['email'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Missing required fields'
                ]);
                exit;
            }
            
            $user_id = intval($input['user_id']);
            $name = trim($input['name']);
            $email = trim($input['email']);
            $phone = isset($input['phone']) ? trim($input['phone']) : null;
            
            // Validate input
            if (empty($name) || empty($email)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Name and Email cannot be empty'
                ]);
                exit;
            }
            
            // Check if email already exists for another user
            $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $stmt->bind_param("si", $email, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Email already exists for another user'
                ]);
                exit;
            }
            
            // Update user
            $updateSql = "UPDATE users SET name = ?, email = ?, phone = ? WHERE id = ?";
            $stmt = $conn->prepare($updateSql);
            
            if (!$stmt) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $conn->error
                ]);
                exit;
            }
            
            $stmt->bind_param("sssi", $name, $email, $phone, $user_id);
            
            if ($stmt->execute()) {
                echo json_encode([
                    'success' => true,
                    'message' => 'User updated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to update user: ' . $stmt->error
                ]);
            }
            $stmt->close();
            
        } elseif ($action === 'delete') {
            // Validate required fields
            if (!isset($input['user_id'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'User ID is required'
                ]);
                exit;
            }
            
            $user_id = intval($input['user_id']);
            
            // Prevent deleting admin users (optional - add check if you have admin flag)
            // For now, allow deletion
            
            // Delete user
            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            
            if (!$stmt) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $conn->error
                ]);
                exit;
            }
            
            $stmt->bind_param("i", $user_id);
            
            if ($stmt->execute()) {
                if ($stmt->affected_rows > 0) {
                    echo json_encode([
                        'success' => true,
                        'message' => 'User deleted successfully'
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'message' => 'User not found'
                    ]);
                }
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to delete user: ' . $stmt->error
                ]);
            }
            $stmt->close();
            
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action: ' . $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();
?>

