<?php
// Chefs API for managing chef details, skills, and social media
session_start();
header('Content-Type: application/json');

include 'config.php';

// Get action from query parameter
$action = isset($_GET['action']) ? $_GET['action'] : null;

try {
    if (!$action) {
        throw new Exception('No action specified');
    }

    // Handle image upload
    if ($action === 'upload_image') {
        handleImageUpload();
        return;
    }

    // Chef operations
    if ($action === 'create_chef') {
        createChef();
    } elseif ($action === 'get_chefs') {
        getChefs();
    } elseif ($action === 'get_chef') {
        getChef();
    } elseif ($action === 'update_chef') {
        updateChef();
    } elseif ($action === 'delete_chef') {
        deleteChef();
    }
    // Skill operations
    elseif ($action === 'add_skill') {
        addSkill();
    } elseif ($action === 'delete_skill') {
        deleteSkill();
    }
    // Social media operations
    elseif ($action === 'add_social') {
        addSocialMedia();
    } elseif ($action === 'delete_social') {
        deleteSocialMedia();
    }
    // Public endpoints
    elseif ($action === 'get_all_chefs') {
        getAllChefsForClient();
    } else {
        throw new Exception('Invalid action');
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// ==================== FUNCTIONS ====================

// Create chef
function createChef() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['name']) || empty($data['position']) || empty($data['image_path'])) {
        throw new Exception('Chef name, position, and image are required');
    }

    $name = htmlspecialchars($data['name']);
    $position = htmlspecialchars($data['position']);
    $description = isset($data['description']) ? htmlspecialchars($data['description']) : '';
    $image_path = htmlspecialchars($data['image_path']);
    $display_order = isset($data['display_order']) ? intval($data['display_order']) : 0;
    
    // Authentication fields (optional)
    $email = isset($data['email']) && !empty($data['email']) ? htmlspecialchars($data['email']) : null;
    $employee_id = isset($data['employee_id']) && !empty($data['employee_id']) ? htmlspecialchars($data['employee_id']) : null;
    $password = isset($data['password']) && !empty($data['password']) ? password_hash($data['password'], PASSWORD_BCRYPT) : null;
    $role = isset($data['role']) && !empty($data['role']) ? htmlspecialchars($data['role']) : 'Chef';
    $status = isset($data['status']) && !empty($data['status']) ? htmlspecialchars($data['status']) : 'active';

    // Check for duplicate email if provided
    if ($email) {
        $check_query = "SELECT id FROM chefs WHERE email = ? AND email IS NOT NULL";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param('s', $email);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception('Email already in use');
        }
        $check_stmt->close();
    }

    // Check for duplicate employee_id if provided
    if ($employee_id) {
        $check_query = "SELECT id FROM chefs WHERE employee_id = ? AND employee_id IS NOT NULL";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param('s', $employee_id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception('Employee ID already in use');
        }
        $check_stmt->close();
    }

    $query = "INSERT INTO chefs (name, position, description, image_path, display_order, email, employee_id, password, role, status, created_at) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('ssssisssss', $name, $position, $description, $image_path, $display_order, $email, $employee_id, $password, $role, $status);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Chef created successfully',
            'data' => [
                'id' => $stmt->insert_id,
                'name' => $name
            ]
        ]);
    } else {
        throw new Exception('Failed to create chef: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Get all chefs
function getChefs() {
    global $conn;
    
    $query = "SELECT c.id, c.name, c.position, c.description, c.image_path, c.display_order, 
                     c.email, c.employee_id, c.role, c.status 
              FROM chefs c 
              ORDER BY c.display_order ASC, c.created_at DESC";
    $result = $conn->query($query);
    
    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $chefs = [];
    while ($row = $result->fetch_assoc()) {
        $chefs[] = $row;
    }

    echo json_encode([
        'success' => true,
        'data' => $chefs
    ]);
}

// Get single chef with skills and social media
function getChef() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    
    if (!$id) {
        throw new Exception('Chef ID is required');
    }

    // Get chef details including auth fields
    $query = "SELECT id, name, position, description, image_path, display_order, 
                     email, employee_id, role, status FROM chefs WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Chef not found');
    }

    $chef = $result->fetch_assoc();
    $stmt->close();

    // Get skills
    $skills_query = "SELECT id, skill_name, skill_level FROM chef_skills WHERE chef_id = ?";
    $skills_stmt = $conn->prepare($skills_query);
    $skills_stmt->bind_param('i', $id);
    $skills_stmt->execute();
    $skills_result = $skills_stmt->get_result();
    $chef['skills'] = [];
    while ($row = $skills_result->fetch_assoc()) {
        $chef['skills'][] = $row;
    }
    $skills_stmt->close();

    // Get social media
    $social_query = "SELECT id, platform, url, icon_class FROM chef_social_media WHERE chef_id = ?";
    $social_stmt = $conn->prepare($social_query);
    $social_stmt->bind_param('i', $id);
    $social_stmt->execute();
    $social_result = $social_stmt->get_result();
    $chef['social_media'] = [];
    while ($row = $social_result->fetch_assoc()) {
        $chef['social_media'][] = $row;
    }
    $social_stmt->close();
    
    echo json_encode([
        'success' => true,
        'data' => $chef
    ]);
}

// Update chef
function updateChef() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id']) || empty($data['name']) || empty($data['position'])) {
        throw new Exception('Chef ID, name, and position are required');
    }

    $id = intval($data['id']);
    $name = htmlspecialchars($data['name']);
    $position = htmlspecialchars($data['position']);
    $description = isset($data['description']) ? htmlspecialchars($data['description']) : '';
    $image_path = isset($data['image_path']) ? htmlspecialchars($data['image_path']) : null;
    $display_order = isset($data['display_order']) ? intval($data['display_order']) : 0;
    
    // Authentication fields (optional)
    $email = isset($data['email']) && !empty($data['email']) ? htmlspecialchars($data['email']) : null;
    $employee_id = isset($data['employee_id']) && !empty($data['employee_id']) ? htmlspecialchars($data['employee_id']) : null;
    $password = isset($data['password']) && !empty($data['password']) ? password_hash($data['password'], PASSWORD_BCRYPT) : null;
    $role = isset($data['role']) && !empty($data['role']) ? htmlspecialchars($data['role']) : 'Chef';
    $status = isset($data['status']) && !empty($data['status']) ? htmlspecialchars($data['status']) : 'active';

    // Check for duplicate email if email changed (exclude current chef)
    if ($email) {
        $check_query = "SELECT id FROM chefs WHERE email = ? AND email IS NOT NULL AND id != ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param('si', $email, $id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception('Email already in use by another chef');
        }
        $check_stmt->close();
    }

    // Check for duplicate employee_id if provided (exclude current chef)
    if ($employee_id) {
        $check_query = "SELECT id FROM chefs WHERE employee_id = ? AND employee_id IS NOT NULL AND id != ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param('si', $employee_id, $id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception('Employee ID already in use by another chef');
        }
        $check_stmt->close();
    }

    if ($image_path) {
        $query = "UPDATE chefs SET name = ?, position = ?, description = ?, image_path = ?, display_order = ?, 
                  email = ?, employee_id = ?, " . ($password ? "password = ?, " : "") . "role = ?, status = ?, updated_at = NOW() 
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        if ($password) {
            $stmt->bind_param('ssssissssi', $name, $position, $description, $image_path, $display_order, $email, $employee_id, $password, $role, $status, $id);
        } else {
            $stmt->bind_param('ssssissssi', $name, $position, $description, $image_path, $display_order, $email, $employee_id, $role, $status, $id);
        }
    } else {
        $query = "UPDATE chefs SET name = ?, position = ?, description = ?, display_order = ?, 
                  email = ?, employee_id = ?, " . ($password ? "password = ?, " : "") . "role = ?, status = ?, updated_at = NOW() 
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        if ($password) {
            $stmt->bind_param('sssisssssi', $name, $position, $description, $display_order, $email, $employee_id, $password, $role, $status, $id);
        } else {
            $stmt->bind_param('sssissssi', $name, $position, $description, $display_order, $email, $employee_id, $role, $status, $id);
        }
    }
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Chef updated successfully'
        ]);
    } else {
        throw new Exception('Failed to update chef: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Delete chef
function deleteChef() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        throw new Exception('Chef ID is required');
    }

    $id = intval($data['id']);

    // Get chef image to delete file
    $query = "SELECT image_path FROM chefs WHERE id = ?";
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $file_path = '../' . $row['image_path'];
        
        // Delete file from server
        if (file_exists($file_path)) {
            unlink($file_path);
        }
    }
    $stmt->close();

    // Delete chef (skills and social media will be deleted via CASCADE)
    $delete_query = "DELETE FROM chefs WHERE id = ?";
    $delete_stmt = $conn->prepare($delete_query);
    
    if (!$delete_stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $delete_stmt->bind_param('i', $id);
    
    if ($delete_stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Chef deleted successfully'
        ]);
    } else {
        throw new Exception('Failed to delete chef: ' . $delete_stmt->error);
    }
    
    $delete_stmt->close();
}

// Upload image
function handleImageUpload() {
    if (!isset($_FILES['image'])) {
        echo json_encode([
            'success' => false,
            'message' => 'No image file provided'
        ]);
        return;
    }

    $file = $_FILES['image'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid image format. Allowed: JPG, PNG, GIF, WebP'
        ]);
        return;
    }

    $max_size = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $max_size) {
        echo json_encode([
            'success' => false,
            'message' => 'Image size exceeds 5MB limit'
        ]);
        return;
    }

    // Create upload directory if it doesn't exist
    $upload_dir = '../assets/uploads/chefs/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Generate unique filename
    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file_name = 'chef_' . time() . '_' . uniqid() . '.' . $file_ext;
    $file_path = $upload_dir . $file_name;

    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        echo json_encode([
            'success' => true,
            'data' => [
                'path' => 'assets/uploads/chefs/' . $file_name,
                'name' => $file_name
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to upload image'
        ]);
    }
}

// Add skill to chef
function addSkill() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['chef_id']) || empty($data['skill_name'])) {
        throw new Exception('Chef ID and skill name are required');
    }

    $chef_id = intval($data['chef_id']);
    $skill_name = htmlspecialchars($data['skill_name']);
    $skill_level = isset($data['skill_level']) ? htmlspecialchars($data['skill_level']) : 'Expert';

    $query = "INSERT INTO chef_skills (chef_id, skill_name, skill_level) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('iss', $chef_id, $skill_name, $skill_level);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Skill added successfully',
            'data' => [
                'id' => $stmt->insert_id,
                'skill_name' => $skill_name
            ]
        ]);
    } else {
        throw new Exception('Failed to add skill: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Delete skill
function deleteSkill() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        throw new Exception('Skill ID is required');
    }

    $id = intval($data['id']);

    $query = "DELETE FROM chef_skills WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Skill deleted successfully'
        ]);
    } else {
        throw new Exception('Failed to delete skill: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Add social media
function addSocialMedia() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['chef_id']) || empty($data['platform']) || empty($data['url'])) {
        throw new Exception('Chef ID, platform, and URL are required');
    }

    $chef_id = intval($data['chef_id']);
    $platform = htmlspecialchars($data['platform']);
    $url = htmlspecialchars($data['url']);
    $icon_class = isset($data['icon_class']) ? htmlspecialchars($data['icon_class']) : 'fab fa-' . strtolower($platform);

    $query = "INSERT INTO chef_social_media (chef_id, platform, url, icon_class) 
              VALUES (?, ?, ?, ?) 
              ON DUPLICATE KEY UPDATE url = ?, icon_class = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('isssss', $chef_id, $platform, $url, $icon_class, $url, $icon_class);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Social media added successfully'
        ]);
    } else {
        throw new Exception('Failed to add social media: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Delete social media
function deleteSocialMedia() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        throw new Exception('Social media ID is required');
    }

    $id = intval($data['id']);

    $query = "DELETE FROM chef_social_media WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Social media deleted successfully'
        ]);
    } else {
        throw new Exception('Failed to delete social media: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Get all chefs for client
function getAllChefsForClient() {
    global $conn;
    
    $query = "SELECT c.id, c.name, c.position, c.description, c.image_path, c.display_order 
              FROM chefs c 
              ORDER BY c.display_order ASC, c.created_at DESC";
    $result = $conn->query($query);
    
    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $chefs = [];
    while ($row = $result->fetch_assoc()) {
        $chef_id = $row['id'];
        
        // Get skills
        $skills_query = "SELECT skill_name FROM chef_skills WHERE chef_id = ?";
        $skills_stmt = $conn->prepare($skills_query);
        $skills_stmt->bind_param('i', $chef_id);
        $skills_stmt->execute();
        $skills_result = $skills_stmt->get_result();
        $skills = [];
        while ($skill = $skills_result->fetch_assoc()) {
            $skills[] = $skill['skill_name'];
        }
        $skills_stmt->close();
        $row['skills'] = $skills;
        
        // Get social media
        $social_query = "SELECT platform, url, icon_class FROM chef_social_media WHERE chef_id = ?";
        $social_stmt = $conn->prepare($social_query);
        $social_stmt->bind_param('i', $chef_id);
        $social_stmt->execute();
        $social_result = $social_stmt->get_result();
        $social = [];
        while ($soc = $social_result->fetch_assoc()) {
            $social[] = [
                'platform' => $soc['platform'],
                'url' => $soc['url'],
                'icon_class' => $soc['icon_class']
            ];
        }
        $social_stmt->close();
        $row['social_media'] = $social;
        
        $chefs[] = $row;
    }

    echo json_encode([
        'success' => true,
        'data' => $chefs
    ]);
}

?>
