<?php
/**
 * API Handler for Admin Dashboard
 * Handles all CRUD operations for different sections
 * Returns JSON responses for real-time integration
 */

require_once 'config.php';
session_start();

// Set JSON response header first (before any other output)
header('Content-Type: application/json');

// Get action from request
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

// Allow staff login without authentication check
if ($action === 'staff_login') {
    staffLogin();
    exit();
}

// Allow public API endpoints (accessible by guests and all users)
$public_endpoints = array('get_services', 'get_blog_posts', 'get_approved_reviews', 'get_service_details', 'get_blog_details');

// Check if this is a public endpoint
$is_public = in_array($action, $public_endpoints);

// Check authentication only for admin/staff endpoints
if (!$is_public) {
    if (!isset($_SESSION['user_id']) || ($_SESSION['user_type'] !== 'admin' && $_SESSION['user_type'] !== 'staff')) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit();
    }
}

// Route to appropriate handler
switch ($action) {
    // RESERVATIONS/BOOKINGS
    case 'get_bookings':
        getBookings();
        break;
    case 'get_booking_details':
        getBookingDetails();
        break;
    case 'add_booking':
        addBooking();
        break;
    case 'edit_booking':
        editBooking();
        break;
    case 'delete_booking':
        deleteBooking();
        break;
    case 'approve_booking':
        approveBooking();
        break;
    case 'reject_booking':
        rejectBooking();
        break;

    // CUSTOMERS
    case 'get_customers':
        getCustomers();
        break;
    case 'get_customer_details':
        getCustomerDetails();
        break;
    case 'add_customer':
        addCustomer();
        break;
    case 'edit_customer':
        editCustomer();
        break;
    case 'delete_customer':
        deleteCustomer();
        break;

    // SERVICES
    case 'get_services':
        getServices();
        break;
    case 'get_service_details':
        getServiceDetails();
        break;
    case 'add_service':
        addService();
        break;
    case 'edit_service':
        editService();
        break;
    case 'delete_service':
        deleteService();
        break;

    // TEAM
    case 'get_team':
        getTeam();
        break;
    case 'get_team_member_details':
        getTeamMemberDetails();
        break;
    case 'add_team_member':
        addTeamMember();
        break;
    case 'edit_team_member':
        editTeamMember();
        break;
    case 'delete_team_member':
        deleteTeamMember();
        break;

    // BLOG
    case 'get_blog_posts':
        getBlogPosts();
        break;
    case 'get_blog_details':
        getBlogDetails();
        break;
    case 'add_blog':
        addBlog();
        break;
    case 'edit_blog':
        editBlog();
        break;
    case 'delete_blog':
        deleteBlog();
        break;

    // GALLERY
    case 'get_gallery':
        getGallery();
        break;
    case 'add_gallery':
        addGallery();
        break;
    case 'delete_gallery':
        deleteGallery();
        break;

    // CONTACT MESSAGES
    case 'get_contact_messages':
        getContactMessages();
        break;
    case 'get_contact_detail':
        getContactDetail();
        break;
    case 'mark_contact_read':
        markContactRead();
        break;
    case 'delete_contact':
        deleteContact();
        break;

    // FEEDBACK/REVIEWS
    case 'get_feedback':
        getFeedback();
        break;
    case 'get_approved_reviews':
        getApprovedReviews();
        break;
    case 'approve_feedback':
        approveFeedback();
        break;
    case 'delete_feedback':
        deleteFeedback();
        break;

    // TEST ENDPOINTS (for debugging)
    case 'test_reviews_table':
        testReviewsTable();
        break;
    case 'test_approved_count':
        testApprovedCount();
        break;
    case 'test_all_reviews':
        testAllReviews();
        break;

    // ADMIN PROFILE
    case 'get_admin_profile':
        getAdminProfile();
        break;
    case 'update_admin_profile':
        updateAdminProfile();
        break;

    // STAFF MANAGEMENT
    case 'get_staff':
        getStaff();
        break;
    case 'get_staff_details':
        getStaffDetails();
        break;
    case 'add_staff':
        addStaff();
        break;
    case 'edit_staff':
        editStaff();
        break;
    case 'delete_staff':
        deleteStaff();
        break;

    // STAFF DASHBOARD
    case 'get_staff_stats':
        getStaffStats();
        break;
    case 'get_staff_profile':
        getStaffProfile();
        break;
    case 'get_staff_upcoming_assignments':
        getStaffUpcomingAssignments();
        break;
    case 'get_staff_assignments':
        getStaffAssignments();
        break;
    case 'complete_staff_assignment':
        completeStaffAssignment();
        break;
    case 'update_staff_profile':
        updateStaffProfile();
        break;

    // TASK ASSIGNMENTS
    case 'assign_task':
        assignTask();
        break;
    case 'get_task_assignments':
        getTaskAssignments();
        break;
    case 'get_staff_task_assignments':
        getStaffTaskAssignments();
        break;
    case 'update_task_status':
        updateTaskStatus();
        break;
    case 'delete_task_assignment':
        deleteTaskAssignment();
        break;

    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}

// RESERVATION/BOOKING FUNCTIONS
function getBookings() {
    global $conn;
    $status = isset($_GET['status']) ? $_GET['status'] : '';
    
    $query = "SELECT b.*, u.name as customer_name, u.email, u.phone, s.name as service_name, s.price 
              FROM bookings b 
              JOIN users u ON b.user_id = u.id 
              JOIN services s ON b.service_id = s.id";
    
    if (!empty($status)) {
        $query .= " WHERE b.status = '$status'";
    }
    
    $query .= " ORDER BY b.created_at DESC";
    
    $result = $conn->query($query);
    $bookings = [];
    
    while ($row = $result->fetch_assoc()) {
        // If total_amount is not set or null, calculate it from price
        if (!$row['total_amount'] || $row['total_amount'] == 0) {
            $row['total_amount'] = $row['price'];
        }
        $bookings[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $bookings]);
}

function getBookingDetails() {
    global $conn;
    $booking_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$booking_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid booking ID']);
        return;
    }
    
    $query = "SELECT b.*, u.name as customer_name, u.email, u.phone, u.address, u.city, s.name as service_name, s.price, s.description 
              FROM bookings b 
              JOIN users u ON b.user_id = u.id 
              JOIN services s ON b.service_id = s.id 
              WHERE b.id = $booking_id";
    
    $result = $conn->query($query);
    $booking = $result->fetch_assoc();
    
    if ($booking) {
        echo json_encode(['success' => true, 'data' => $booking]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Booking not found']);
    }
}

function addBooking() {
    global $conn;
    
    $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
    $service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
    $booking_date = isset($_POST['booking_date']) ? $_POST['booking_date'] : '';
    $booking_time = isset($_POST['booking_time']) ? $_POST['booking_time'] : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    if (!$user_id || !$service_id || !$booking_date || !$booking_time) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        return;
    }
    
    // Get service price
    $service_query = "SELECT price, duration FROM services WHERE id = $service_id";
    $service_result = $conn->query($service_query);
    $service = $service_result->fetch_assoc();
    
    $total_amount = $service['price'];
    $duration = $service['duration'];
    
    $query = "INSERT INTO bookings (user_id, service_id, booking_date, booking_time, duration, address, notes, total_amount, status) 
              VALUES ($user_id, $service_id, '$booking_date', '$booking_time', $duration, '$address', '$notes', $total_amount, 'pending')";
    
    if ($conn->query($query)) {
        $booking_id = $conn->insert_id;
        echo json_encode(['success' => true, 'message' => 'Booking added successfully', 'data' => ['id' => $booking_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding booking: ' . $conn->error]);
    }
}

function editBooking() {
    global $conn;
    
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    $booking_date = isset($_POST['booking_date']) ? $_POST['booking_date'] : '';
    $booking_time = isset($_POST['booking_time']) ? $_POST['booking_time'] : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    if (!$booking_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid booking ID']);
        return;
    }
    
    $query = "UPDATE bookings SET booking_date = '$booking_date', booking_time = '$booking_time', 
              address = '$address', notes = '$notes' WHERE id = $booking_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Booking updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating booking']);
    }
}

function deleteBooking() {
    global $conn;
    
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    
    if (!$booking_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid booking ID']);
        return;
    }
    
    $query = "DELETE FROM bookings WHERE id = $booking_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Booking deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting booking']);
    }
}

function approveBooking() {
    global $conn;
    
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    
    if (!$booking_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid booking ID']);
        return;
    }
    
    $query = "UPDATE bookings SET status = 'confirmed' WHERE id = $booking_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Booking approved successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error approving booking']);
    }
}

function rejectBooking() {
    global $conn;
    
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    
    if (!$booking_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid booking ID']);
        return;
    }
    
    $query = "UPDATE bookings SET status = 'cancelled' WHERE id = $booking_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Booking rejected successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error rejecting booking']);
    }
}

// CUSTOMER FUNCTIONS
function getCustomers() {
    global $conn;
    
    $query = "SELECT u.*, COUNT(b.id) as total_bookings, SUM(b.total_amount) as total_spent 
              FROM users u 
              LEFT JOIN bookings b ON u.id = b.user_id 
              WHERE u.user_type = 'customer' 
              GROUP BY u.id 
              ORDER BY u.created_at DESC";
    
    $result = $conn->query($query);
    $customers = [];
    
    while ($row = $result->fetch_assoc()) {
        $row['total_spent'] = $row['total_spent'] ? number_format($row['total_spent'], 2) : '0.00';
        $customers[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $customers]);
}

function getCustomerDetails() {
    global $conn;
    $customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$customer_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
        return;
    }
    
    $query = "SELECT * FROM users WHERE id = $customer_id AND user_type = 'customer'";
    $result = $conn->query($query);
    $customer = $result->fetch_assoc();
    
    if ($customer) {
        echo json_encode(['success' => true, 'data' => $customer]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
    }
}

function addCustomer() {
    global $conn;
    
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : 'default123';
    
    if (!$name || !$email) {
        echo json_encode(['success' => false, 'message' => 'Name and email are required']);
        return;
    }
    
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    $query = "INSERT INTO users (name, email, phone, address, city, password, user_type, status) 
              VALUES ('$name', '$email', '$phone', '$address', '$city', '$hashed_password', 'customer', 'active')";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Customer added successfully', 'data' => ['id' => $conn->insert_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding customer: ' . $conn->error]);
    }
}

function editCustomer() {
    global $conn;
    
    $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    
    if (!$customer_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
        return;
    }
    
    $query = "UPDATE users SET name = '$name', email = '$email', phone = '$phone', city = '$city', address = '$address' 
              WHERE id = $customer_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Customer updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating customer']);
    }
}

function deleteCustomer() {
    global $conn;
    
    $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    
    if (!$customer_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
        return;
    }
    
    $query = "DELETE FROM users WHERE id = $customer_id AND user_type = 'customer'";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Customer deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting customer']);
    }
}

// SERVICE FUNCTIONS
function getServices() {
    global $conn;
    
    $query = "SELECT *, (SELECT COUNT(*) FROM bookings WHERE service_id = services.id) as bookings_count 
              FROM services 
              ORDER BY created_at DESC";
    
    $result = $conn->query($query);
    $services = [];
    
    while ($row = $result->fetch_assoc()) {
        $services[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $services]);
}

function getServiceDetails() {
    global $conn;
    $service_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$service_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid service ID']);
        return;
    }
    
    $query = "SELECT * FROM services WHERE id = $service_id";
    $result = $conn->query($query);
    $service = $result->fetch_assoc();
    
    if ($service) {
        echo json_encode(['success' => true, 'data' => $service]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Service not found']);
    }
}

function addService() {
    global $conn;
    
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
    $duration = isset($_POST['duration']) ? intval($_POST['duration']) : 60;
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $image = isset($_POST['image']) ? trim($_POST['image']) : '';
    
    if (!$name || !$price) {
        echo json_encode(['success' => false, 'message' => 'Name and price are required']);
        return;
    }
    
    $query = "INSERT INTO services (name, description, price, duration, category, image, status) 
              VALUES ('$name', '$description', $price, $duration, '$category', '$image', 'active')";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Service added successfully', 'data' => ['id' => $conn->insert_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding service']);
    }
}

function editService() {
    global $conn;
    
    $service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
    $duration = isset($_POST['duration']) ? intval($_POST['duration']) : 60;
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $image = isset($_POST['image']) ? trim($_POST['image']) : '';
    
    if (!$service_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid service ID']);
        return;
    }
    
    // If image is provided, update it; otherwise keep the existing one
    if ($image) {
        $query = "UPDATE services SET name = '$name', description = '$description', price = $price, 
                  duration = $duration, category = '$category', image = '$image' WHERE id = $service_id";
    } else {
        $query = "UPDATE services SET name = '$name', description = '$description', price = $price, 
                  duration = $duration, category = '$category' WHERE id = $service_id";
    }
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Service updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating service']);
    }
}

function deleteService() {
    global $conn;
    
    $service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
    
    if (!$service_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid service ID']);
        return;
    }
    
    $query = "DELETE FROM services WHERE id = $service_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Service deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting service']);
    }
}

// TEAM FUNCTIONS
function getTeam() {
    global $conn;
    
    $query = "SELECT * FROM team_members ORDER BY created_at DESC";
    $result = $conn->query($query);
    $team = [];
    
    while ($row = $result->fetch_assoc()) {
        $team[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $team]);
}

function getTeamMemberDetails() {
    global $conn;
    $team_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$team_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid team member ID']);
        return;
    }
    
    $query = "SELECT * FROM team_members WHERE id = $team_id";
    $result = $conn->query($query);
    $member = $result->fetch_assoc();
    
    if ($member) {
        echo json_encode(['success' => true, 'data' => $member]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Team member not found']);
    }
}

function addTeamMember() {
    global $conn;
    
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $position = isset($_POST['position']) ? trim($_POST['position']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $specialization = isset($_POST['specialization']) ? trim($_POST['specialization']) : '';
    $experience = isset($_POST['experience']) ? intval($_POST['experience']) : 0;
    $image = isset($_POST['image']) ? trim($_POST['image']) : '';
    
    if (!$name) {
        echo json_encode(['success' => false, 'message' => 'Name is required']);
        return;
    }
    
    $query = "INSERT INTO team_members (name, position, email, phone, specialization, experience, image, status) 
              VALUES ('$name', '$position', '$email', '$phone', '$specialization', $experience, '$image', 'active')";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Team member added successfully', 'data' => ['id' => $conn->insert_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding team member']);
    }
}

function editTeamMember() {
    global $conn;
    
    $team_id = isset($_POST['team_id']) ? intval($_POST['team_id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $position = isset($_POST['position']) ? trim($_POST['position']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $specialization = isset($_POST['specialization']) ? trim($_POST['specialization']) : '';
    $experience = isset($_POST['experience']) ? intval($_POST['experience']) : 0;
    $image = isset($_POST['image']) ? trim($_POST['image']) : '';
    
    if (!$team_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid team member ID']);
        return;
    }
    
    // If image is provided, update it; otherwise keep the existing one
    if ($image) {
        $query = "UPDATE team_members SET name = '$name', position = '$position', email = '$email', 
                  phone = '$phone', specialization = '$specialization', experience = $experience, image = '$image' WHERE id = $team_id";
    } else {
        $query = "UPDATE team_members SET name = '$name', position = '$position', email = '$email', 
                  phone = '$phone', specialization = '$specialization', experience = $experience WHERE id = $team_id";
    }
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Team member updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating team member']);
    }
}

function deleteTeamMember() {
    global $conn;
    
    $team_id = isset($_POST['team_id']) ? intval($_POST['team_id']) : 0;
    
    if (!$team_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid team member ID']);
        return;
    }
    
    $query = "DELETE FROM team_members WHERE id = $team_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Team member deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting team member']);
    }
}

// BLOG FUNCTIONS
function getBlogPosts() {
    global $conn;
    
    $query = "SELECT b.*, u.name as author_name FROM blog_posts b 
              LEFT JOIN users u ON b.author_id = u.id 
              ORDER BY b.created_at DESC";
    
    $result = $conn->query($query);
    $posts = [];
    
    while ($row = $result->fetch_assoc()) {
        $posts[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $posts]);
}

function getBlogDetails() {
    global $conn;
    $blog_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$blog_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
        return;
    }
    
    $query = "SELECT * FROM blog_posts WHERE id = $blog_id";
    $result = $conn->query($query);
    $post = $result->fetch_assoc();
    
    if ($post) {
        echo json_encode(['success' => true, 'data' => $post]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Blog post not found']);
    }
}

function addBlog() {
    global $conn;
    
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $featured_image = isset($_POST['image']) ? trim($_POST['image']) : '';
    $author_id = isset($_POST['author_id']) ? intval($_POST['author_id']) : $_SESSION['user_id'];
    
    if (!$title || !$content) {
        echo json_encode(['success' => false, 'message' => 'Title and content are required']);
        return;
    }
    
    $slug = strtolower(preg_replace('/[^a-z0-9]+/', '-', $title));
    
    $query = "INSERT INTO blog_posts (title, slug, content, featured_image, author_id, category, status) 
              VALUES ('$title', '$slug', '$content', '$featured_image', $author_id, '$category', 'published')";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Blog post added successfully', 'data' => ['id' => $conn->insert_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding blog post']);
    }
}

function editBlog() {
    global $conn;
    
    $blog_id = isset($_POST['blog_id']) ? intval($_POST['blog_id']) : 0;
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $featured_image = isset($_POST['image']) ? trim($_POST['image']) : '';
    
    if (!$blog_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
        return;
    }
    
    $slug = strtolower(preg_replace('/[^a-z0-9]+/', '-', $title));
    
    // If image is provided, update it; otherwise keep the existing one
    if ($featured_image) {
        $query = "UPDATE blog_posts SET title = '$title', slug = '$slug', content = '$content', featured_image = '$featured_image', category = '$category' WHERE id = $blog_id";
    } else {
        $query = "UPDATE blog_posts SET title = '$title', slug = '$slug', content = '$content', category = '$category' WHERE id = $blog_id";
    }
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Blog post updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating blog post']);
    }
}

function deleteBlog() {
    global $conn;
    
    $blog_id = isset($_POST['blog_id']) ? intval($_POST['blog_id']) : 0;
    
    if (!$blog_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
        return;
    }
    
    $query = "DELETE FROM blog_posts WHERE id = $blog_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Blog post deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting blog post']);
    }
}

// GALLERY FUNCTIONS
function getGallery() {
    global $conn;
    
    $query = "SELECT g.*, s.name as service_name FROM gallery g 
              LEFT JOIN services s ON g.service_id = s.id 
              ORDER BY g.created_at DESC";
    
    $result = $conn->query($query);
    $gallery = [];
    
    while ($row = $result->fetch_assoc()) {
        $gallery[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $gallery]);
}

function addGallery() {
    global $conn;
    
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $image_url = isset($_POST['image_url']) ? trim($_POST['image_url']) : '';
    $service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : null;
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    
    if (!$title || !$image_url) {
        echo json_encode(['success' => false, 'message' => 'Title and image URL are required']);
        return;
    }
    
    $service_id = $service_id ? $service_id : 'NULL';
    
    $query = "INSERT INTO gallery (title, description, image_url, service_id, category, status) 
              VALUES ('$title', '$description', '$image_url', $service_id, '$category', 'active')";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Gallery image added successfully', 'data' => ['id' => $conn->insert_id]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding gallery image']);
    }
}

function deleteGallery() {
    global $conn;
    
    $gallery_id = isset($_POST['gallery_id']) ? intval($_POST['gallery_id']) : 0;
    
    if (!$gallery_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid gallery ID']);
        return;
    }
    
    $query = "DELETE FROM gallery WHERE id = $gallery_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Gallery image deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting gallery image']);
    }
}

// CONTACT MESSAGE FUNCTIONS
function getContactMessages() {
    global $conn;
    
    $query = "SELECT * FROM contact_messages ORDER BY created_at DESC";
    $result = $conn->query($query);
    $messages = [];
    
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $messages]);
}

function getContactDetail() {
    global $conn;
    $message_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$message_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid message ID']);
        return;
    }
    
    $query = "SELECT * FROM contact_messages WHERE id = $message_id";
    $result = $conn->query($query);
    $message = $result->fetch_assoc();
    
    if ($message) {
        echo json_encode(['success' => true, 'data' => $message]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Message not found']);
    }
}

function markContactRead() {
    global $conn;
    
    $message_id = isset($_POST['message_id']) ? intval($_POST['message_id']) : 0;
    
    if (!$message_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid message ID']);
        return;
    }
    
    $query = "UPDATE contact_messages SET status = 'read' WHERE id = $message_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Message marked as read']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating message']);
    }
}

function deleteContact() {
    global $conn;
    
    $message_id = isset($_POST['message_id']) ? intval($_POST['message_id']) : 0;
    
    if (!$message_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid message ID']);
        return;
    }
    
    $query = "DELETE FROM contact_messages WHERE id = $message_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Message deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting message']);
    }
}

// FEEDBACK/REVIEWS FUNCTIONS
function getFeedback() {
    global $conn;
    
    // Check if reviews table exists first
    $check_query = "SHOW TABLES LIKE 'reviews'";
    $result = $conn->query($check_query);
    
    if ($result->num_rows == 0) {
        echo json_encode(['success' => true, 'data' => []]);
        return;
    }
    
    // Get all feedback for admin dashboard
    $query = "SELECT r.*, u.name as customer_name FROM reviews r 
              LEFT JOIN users u ON r.user_id = u.id 
              ORDER BY r.created_at DESC";
    
    $result = $conn->query($query);
    $feedback = [];
    
    while ($row = $result->fetch_assoc()) {
        $feedback[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $feedback]);
}

function getApprovedReviews() {
    global $conn;
    
    // Check if reviews table exists first
    $check_query = "SHOW TABLES LIKE 'reviews'";
    $result = $conn->query($check_query);
    
    if (!$result || $result->num_rows == 0) {
        echo json_encode(['success' => true, 'data' => []]);
        return;
    }
    
    // Get only approved reviews for homepage testimonials
    $query = "SELECT r.*, u.name as customer_name FROM reviews r 
              LEFT JOIN users u ON r.user_id = u.id 
              WHERE r.status = 'approved'
              ORDER BY r.created_at DESC 
              LIMIT 20";
    
    $result = $conn->query($query);
    
    if (!$result) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        return;
    }
    
    $reviews = [];
    while ($row = $result->fetch_assoc()) {
        $reviews[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $reviews]);
}

function approveFeedback() {
    global $conn;
    
    $feedback_id = isset($_POST['feedback_id']) ? intval($_POST['feedback_id']) : 0;
    
    if (!$feedback_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid feedback ID']);
        return;
    }
    
    $query = "UPDATE reviews SET status = 'approved' WHERE id = $feedback_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Feedback approved successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error approving feedback']);
    }
}

function deleteFeedback() {
    global $conn;
    
    $feedback_id = isset($_POST['feedback_id']) ? intval($_POST['feedback_id']) : 0;
    
    if (!$feedback_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid feedback ID']);
        return;
    }
    
    $query = "DELETE FROM reviews WHERE id = $feedback_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Feedback deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting feedback']);
    }
}

// ADMIN PROFILE FUNCTIONS
function getAdminProfile() {
    global $conn;
    
    $user_id = $_SESSION['user_id'];
    // Admin profiles are stored in the users table
    $query = "SELECT id, name, email, phone FROM users WHERE id = $user_id";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $profile = $result->fetch_assoc();
        echo json_encode(['success' => true, 'data' => $profile]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Profile not found']);
    }
}

function updateAdminProfile() {
    global $conn;
    
    $user_id = $_SESSION['user_id'];
    $name = isset($_POST['name']) ? $conn->real_escape_string($_POST['name']) : '';
    $email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? $conn->real_escape_string($_POST['phone']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    
    if (!$name) {
        echo json_encode(['success' => false, 'message' => 'Name is required']);
        return;
    }
    
    if (!$email) {
        echo json_encode(['success' => false, 'message' => 'Email is required']);
        return;
    }
    
    // Check if email already exists (excluding current user)
    $checkEmail = "SELECT id FROM users WHERE email = '$email' AND id != $user_id";
    $checkResult = $conn->query($checkEmail);
    if ($checkResult && $checkResult->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Email already in use']);
        return;
    }
    
    $updateQuery = "UPDATE users SET name = '$name', email = '$email', phone = '$phone'";
    
    if ($password) {
        if (strlen($password) < 8) {
            echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters']);
            return;
        }
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        $updateQuery .= ", password = '$hashed_password'";
    }
    
    $updateQuery .= " WHERE id = $user_id";
    
    if ($conn->query($updateQuery)) {
        $_SESSION['admin_name'] = $name;
        echo json_encode(['success' => true, 'message' => 'Profile updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating profile: ' . $conn->error]);
    }
}

// STAFF MANAGEMENT FUNCTIONS
function getStaff() {
    global $conn;
    
    $query = "SELECT id, name, email, phone, position, status, 
              (SELECT COUNT(*) FROM staff_services WHERE staff_id = staff.id) as services_count
              FROM staff ORDER BY name ASC";
    $result = $conn->query($query);
    
    $staff = [];
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $staff[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $staff]);
}

function getStaffDetails() {
    global $conn;
    
    $staff_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$staff_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid staff ID']);
        return;
    }
    
    $query = "SELECT * FROM staff WHERE id = $staff_id";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $staff = $result->fetch_assoc();
        
        // Get assigned services
        $servicesQuery = "SELECT service_id as id FROM staff_services WHERE staff_id = $staff_id";
        $servicesResult = $conn->query($servicesQuery);
        $services = [];
        
        if ($servicesResult) {
            while ($service = $servicesResult->fetch_assoc()) {
                $services[] = $service;
            }
        }
        
        $staff['services'] = $services;
        echo json_encode(['success' => true, 'data' => $staff]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Staff member not found']);
    }
}

function addStaff() {
    global $conn;
    
    $name = isset($_POST['name']) ? $conn->real_escape_string($_POST['name']) : '';
    $email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? $conn->real_escape_string($_POST['phone']) : '';
    $position = isset($_POST['position']) ? $conn->real_escape_string($_POST['position']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $status = isset($_POST['status']) ? $_POST['status'] : 'active';
    $services = isset($_POST['services']) ? json_decode($_POST['services'], true) : [];
    
    if (!$name || !$email || !$phone || !$password) {
        echo json_encode(['success' => false, 'message' => 'Name, email, phone, and password are required']);
        return;
    }
    
    if (strlen($password) < 8) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long']);
        return;
    }
    
    // Check if email already exists
    $checkQuery = "SELECT id FROM staff WHERE email = '$email'";
    $checkResult = $conn->query($checkQuery);
    if ($checkResult && $checkResult->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Email already exists']);
        return;
    }
    
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $query = "INSERT INTO staff (name, email, phone, position, password, status) 
              VALUES ('$name', '$email', '$phone', '$position', '$hashedPassword', '$status')";
    
    if ($conn->query($query)) {
        $staff_id = $conn->insert_id;
        
        // Add services
        if (!empty($services)) {
            foreach ($services as $service_id) {
                $service_id = intval($service_id);
                if ($service_id > 0) {
                    $conn->query("INSERT INTO staff_services (staff_id, service_id) VALUES ($staff_id, $service_id)");
                }
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Staff member added successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding staff member: ' . $conn->error]);
    }
}

function editStaff() {
    global $conn;
    
    $staff_id = isset($_POST['staff_id']) ? intval($_POST['staff_id']) : 0;
    $name = isset($_POST['name']) ? $conn->real_escape_string($_POST['name']) : '';
    $email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? $conn->real_escape_string($_POST['phone']) : '';
    $position = isset($_POST['position']) ? $conn->real_escape_string($_POST['position']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $status = isset($_POST['status']) ? $_POST['status'] : 'active';
    $services = isset($_POST['services']) ? json_decode($_POST['services'], true) : [];
    
    if (!$staff_id || !$name || !$email || !$phone) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        return;
    }
    
    // Validate password if provided
    if ($password && strlen($password) < 8) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long']);
        return;
    }
    
    // Check if email already exists (for other staff members)
    $checkQuery = "SELECT id FROM staff WHERE email = '$email' AND id != $staff_id";
    $checkResult = $conn->query($checkQuery);
    if ($checkResult && $checkResult->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Email already exists']);
        return;
    }
    
    // Build query based on whether password is provided
    if ($password) {
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
        $query = "UPDATE staff SET name = '$name', email = '$email', phone = '$phone', position = '$position', password = '$hashedPassword', status = '$status' 
                  WHERE id = $staff_id";
    } else {
        $query = "UPDATE staff SET name = '$name', email = '$email', phone = '$phone', position = '$position', status = '$status' 
                  WHERE id = $staff_id";
    }
    
    if ($conn->query($query)) {
        // Update services
        $conn->query("DELETE FROM staff_services WHERE staff_id = $staff_id");
        
        if (!empty($services)) {
            foreach ($services as $service_id) {
                $service_id = intval($service_id);
                if ($service_id > 0) {
                    $conn->query("INSERT INTO staff_services (staff_id, service_id) VALUES ($staff_id, $service_id)");
                }
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Staff member updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating staff member']);
    }
}

function deleteStaff() {
    global $conn;
    
    $staff_id = isset($_POST['staff_id']) ? intval($_POST['staff_id']) : 0;
    
    if (!$staff_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid staff ID']);
        return;
    }
    
    // Delete staff services first
    $conn->query("DELETE FROM staff_services WHERE staff_id = $staff_id");
    
    // Delete staff
    $query = "DELETE FROM staff WHERE id = $staff_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Staff member deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting staff member']);
    }
}

// STAFF LOGIN
function staffLogin() {
    global $conn;
    
    $email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $remember_me = isset($_POST['remember_me']) ? $_POST['remember_me'] : '0';
    
    if (!$email || !$password) {
        echo json_encode(['success' => false, 'message' => 'Email and password are required']);
        return;
    }
    
    // Check if staff exists
    $query = "SELECT id, name, email, phone, position, password, status FROM staff WHERE email = '$email'";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $staff = $result->fetch_assoc();
        
        // Check status
        if ($staff['status'] !== 'active') {
            echo json_encode(['success' => false, 'message' => 'Your account is inactive. Contact admin.']);
            return;
        }
        
        // Verify password (for now using plain text, should use password_hash in production)
        if ($password === $staff['password'] || password_verify($password, $staff['password'])) {
            // Set session
            $_SESSION['user_id'] = $staff['id'];
            $_SESSION['admin_name'] = $staff['name'];
            $_SESSION['user_type'] = 'staff';
            $_SESSION['staff_email'] = $staff['email'];
            
            // Remember me - set cookie for 30 days
            if ($remember_me === '1') {
                setcookie('staff_id', $staff['id'], time() + (30 * 24 * 60 * 60), '/');
                setcookie('staff_email', $staff['email'], time() + (30 * 24 * 60 * 60), '/');
            }
            
            echo json_encode(['success' => true, 'message' => 'Login successful']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid password']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Staff member not found']);
    }
}

// STAFF DASHBOARD FUNCTIONS
function getStaffStats() {
    global $conn;
    
    $staff_id = $_SESSION['user_id'];
    
    $stats = [
        'total_assignments' => 0,
        'pending_assignments' => 0,
        'confirmed_assignments' => 0,
        'completed_assignments' => 0,
        'total_tasks' => 0,
        'pending_tasks' => 0,
        'completed_tasks' => 0
    ];
    
    // Get all assignments for staff
    $query = "SELECT COUNT(*) as count FROM bookings WHERE id IN 
              (SELECT booking_id FROM staff_bookings WHERE staff_id = $staff_id)";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['total_assignments'] = $row['count'];
    }
    
    // Get pending assignments
    $query = "SELECT COUNT(*) as count FROM bookings WHERE status = 'pending' AND id IN 
              (SELECT booking_id FROM staff_bookings WHERE staff_id = $staff_id)";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['pending_assignments'] = $row['count'];
    }
    
    // Get confirmed assignments
    $query = "SELECT COUNT(*) as count FROM bookings WHERE status = 'confirmed' AND id IN 
              (SELECT booking_id FROM staff_bookings WHERE staff_id = $staff_id)";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['confirmed_assignments'] = $row['count'];
    }
    
    // Get completed assignments
    $query = "SELECT COUNT(*) as count FROM bookings WHERE status = 'completed' AND id IN 
              (SELECT booking_id FROM staff_bookings WHERE staff_id = $staff_id)";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['completed_assignments'] = $row['count'];
    }
    
    // Get total tasks assigned to staff
    $query = "SELECT COUNT(*) as count FROM staff_assignments WHERE staff_id = $staff_id";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['total_tasks'] = $row['count'];
    }
    
    // Get pending tasks
    $query = "SELECT COUNT(*) as count FROM staff_assignments WHERE staff_id = $staff_id AND status IN ('pending', 'in_progress')";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['pending_tasks'] = $row['count'];
    }
    
    // Get completed tasks
    $query = "SELECT COUNT(*) as count FROM staff_assignments WHERE staff_id = $staff_id AND status = 'completed'";
    $result = $conn->query($query);
    if ($result) {
        $row = $result->fetch_assoc();
        $stats['completed_tasks'] = $row['count'];
    }
    
    echo json_encode(['success' => true, 'data' => $stats]);
}

function getStaffProfile() {
    global $conn;
    
    $staff_id = $_SESSION['user_id'];
    
    $query = "SELECT s.id, s.name, s.email, s.phone, s.position, s.status 
              FROM staff s WHERE s.id = $staff_id";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $staff = $result->fetch_assoc();
        
        // Get assigned services
        $servicesQuery = "SELECT s.id, s.name FROM services s 
                         INNER JOIN staff_services ss ON s.id = ss.service_id 
                         WHERE ss.staff_id = $staff_id";
        $servicesResult = $conn->query($servicesQuery);
        $services = [];
        
        if ($servicesResult) {
            while ($service = $servicesResult->fetch_assoc()) {
                $services[] = $service;
            }
        }
        
        $staff['services'] = $services;
        echo json_encode(['success' => true, 'data' => $staff]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Staff profile not found']);
    }
}

function getStaffUpcomingAssignments() {
    global $conn;
    
    $staff_id = $_SESSION['user_id'];
    
    $query = "SELECT b.id, b.user_id, b.service_id, b.booking_date, b.booking_time, b.status, 
              u.name as customer_name, s.name as service_name 
              FROM bookings b
              INNER JOIN staff_bookings sb ON b.id = sb.booking_id
              INNER JOIN users u ON b.user_id = u.id
              INNER JOIN services s ON b.service_id = s.id
              WHERE sb.staff_id = $staff_id 
              AND b.booking_date >= CURDATE()
              AND b.status IN ('pending', 'confirmed')
              ORDER BY b.booking_date ASC, b.booking_time ASC
              LIMIT 5";
    
    $result = $conn->query($query);
    
    $assignments = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $assignments[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $assignments]);
}

function getStaffAssignments() {
    global $conn;
    
    $staff_id = $_SESSION['user_id'];
    $status = isset($_GET['status']) ? $_GET['status'] : 'all';
    
    $statusFilter = '';
    if ($status !== 'all') {
        $statusFilter = " AND b.status = '$status'";
    }
    
    $query = "SELECT b.id, b.user_id, b.service_id, b.booking_date, b.booking_time, b.address, b.status, 
              u.name as customer_name, s.name as service_name 
              FROM bookings b
              INNER JOIN staff_bookings sb ON b.id = sb.booking_id
              INNER JOIN users u ON b.user_id = u.id
              INNER JOIN services s ON b.service_id = s.id
              WHERE sb.staff_id = $staff_id
              $statusFilter
              ORDER BY b.booking_date DESC, b.booking_time DESC";
    
    $result = $conn->query($query);
    
    $assignments = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $assignments[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $assignments]);
}

function completeStaffAssignment() {
    global $conn;
    
    $assignment_id = isset($_POST['assignment_id']) ? intval($_POST['assignment_id']) : 0;
    
    if (!$assignment_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid assignment ID']);
        return;
    }
    
    $query = "UPDATE bookings SET status = 'completed' WHERE id = $assignment_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Assignment marked as complete']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating assignment']);
    }
}

function updateStaffProfile() {
    global $conn;
    
    // Verify staff is logged in
    if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'staff') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $staff_id = $_SESSION['user_id'];
    $field = isset($_POST['field']) ? $_POST['field'] : '';
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    
    if (!$field) {
        echo json_encode(['success' => false, 'message' => 'Invalid field']);
        return;
    }
    
    // Allow updating specific fields only
    $allowedFields = ['phone', 'email', 'password'];
    if (!in_array($field, $allowedFields)) {
        echo json_encode(['success' => false, 'message' => 'Invalid field']);
        return;
    }
    
    if (empty($value)) {
        echo json_encode(['success' => false, 'message' => 'Value is required']);
        return;
    }
    
    // Special validation for email
    if ($field === 'email') {
        // Check if email already exists
        $checkQuery = "SELECT id FROM staff WHERE email = '$value' AND id != $staff_id";
        $checkResult = $conn->query($checkQuery);
        if ($checkResult && $checkResult->num_rows > 0) {
            echo json_encode(['success' => false, 'message' => 'Email already in use by another staff member']);
            return;
        }
        $value = $conn->real_escape_string($value);
        $query = "UPDATE staff SET email = '$value' WHERE id = $staff_id";
    } 
    // Special handling for password
    elseif ($field === 'password') {
        if (strlen($value) < 8) {
            echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long']);
            return;
        }
        $hashedPassword = password_hash($value, PASSWORD_BCRYPT);
        $query = "UPDATE staff SET password = '$hashedPassword' WHERE id = $staff_id";
    } 
    // For other fields
    else {
        $value = $conn->real_escape_string($value);
        $query = "UPDATE staff SET $field = '$value' WHERE id = $staff_id";
    }
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => ucfirst($field) . ' updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating profile']);
    }
}

// TASK ASSIGNMENT FUNCTIONS
function assignTask() {
    global $conn;
    
    // Verify admin is logged in
    if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized - must be logged in as admin']);
        return;
    }
    
    $admin_id = $_SESSION['user_id'];
    $staff_id = isset($_POST['staff_id']) ? intval($_POST['staff_id']) : 0;
    $task_description = isset($_POST['task_description']) ? $_POST['task_description'] : '';
    $due_date = isset($_POST['due_date']) ? $_POST['due_date'] : '';
    $priority = isset($_POST['priority']) ? $_POST['priority'] : 'medium';
    
    // Validation
    if (!$staff_id) {
        echo json_encode(['success' => false, 'message' => 'Staff member ID is required']);
        return;
    }
    if (empty($task_description)) {
        echo json_encode(['success' => false, 'message' => 'Task description is required']);
        return;
    }
    if (empty($due_date)) {
        echo json_encode(['success' => false, 'message' => 'Due date is required']);
        return;
    }
    
    // Verify staff member exists
    $checkStaff = $conn->query("SELECT id FROM staff WHERE id = $staff_id");
    if (!$checkStaff || $checkStaff->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid staff member selected']);
        return;
    }
    
    // Escape values
    $task_description = $conn->real_escape_string($task_description);
    $priority = $conn->real_escape_string($priority);
    
    $query = "INSERT INTO staff_assignments (admin_id, staff_id, task_description, due_date, priority, status, admin_status, staff_status) 
              VALUES ($admin_id, $staff_id, '$task_description', '$due_date', '$priority', 'pending', 'pending', 'pending')";
    
    if ($conn->query($query)) {
        $assignment_id = $conn->insert_id;
        echo json_encode(['success' => true, 'message' => 'Task assigned successfully', 'assignment_id' => $assignment_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
    }
}

function getTaskAssignments() {
    global $conn;
    
    // Verify admin is logged in
    if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $admin_id = $_SESSION['user_id'];
    $status = isset($_GET['status']) ? $_GET['status'] : 'all';
    $staff_id = isset($_GET['staff_id']) ? intval($_GET['staff_id']) : 0;
    
    $statusFilter = '';
    if ($status !== 'all') {
        $statusFilter = " AND ta.status = '$status'";
    }
    
    $staffFilter = '';
    if ($staff_id > 0) {
        $staffFilter = " AND ta.staff_id = $staff_id";
    }
    
    $query = "SELECT ta.id, ta.admin_id, ta.staff_id, ta.task_description, ta.due_date, ta.priority, 
              ta.status, ta.admin_status, ta.staff_status, ta.staff_notes, ta.created_at, ta.updated_at,
              s.name as staff_name, s.email as staff_email
              FROM staff_assignments ta
              INNER JOIN staff s ON ta.staff_id = s.id
              WHERE ta.admin_id = $admin_id
              $statusFilter
              $staffFilter
              ORDER BY ta.created_at DESC";
    
    $result = $conn->query($query);
    
    $assignments = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $assignments[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $assignments]);
}

function getStaffTaskAssignments() {
    global $conn;
    
    // Verify staff is logged in
    if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'staff') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $staff_id = $_SESSION['user_id'];
    $status = isset($_GET['status']) ? $_GET['status'] : 'all';
    
    $statusFilter = '';
    if ($status !== 'all') {
        $statusFilter = " AND ta.status = '$status'";
    }
    
    $query = "SELECT ta.id, ta.admin_id, ta.staff_id, ta.task_description, ta.due_date, ta.priority, 
              ta.status, ta.admin_status, ta.staff_status, ta.staff_notes, ta.created_at, ta.updated_at,
              s.name as admin_name, s.email as admin_email
              FROM staff_assignments ta
              INNER JOIN staff s ON ta.admin_id = s.id
              WHERE ta.staff_id = $staff_id
              $statusFilter
              ORDER BY ta.due_date ASC, ta.created_at DESC";
    
    $result = $conn->query($query);
    
    $assignments = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $assignments[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $assignments]);
}

function updateTaskStatus() {
    global $conn;
    
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $assignment_id = isset($_POST['assignment_id']) ? intval($_POST['assignment_id']) : 0;
    $user_type = $_SESSION['user_type'];
    $new_status = isset($_POST['status']) ? $_POST['status'] : '';
    $notes = isset($_POST['notes']) ? $_POST['notes'] : '';
    
    if (!$assignment_id || empty($new_status)) {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        return;
    }
    
    // Get current assignment
    $query = "SELECT * FROM staff_assignments WHERE id = $assignment_id";
    $result = $conn->query($query);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Assignment not found']);
        return;
    }
    
    $assignment = $result->fetch_assoc();
    
    // Check authorization
    if ($user_type === 'admin' && $assignment['admin_id'] !== $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'You cannot update this assignment']);
        return;
    }
    
    if ($user_type === 'staff' && $assignment['staff_id'] !== $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'You cannot update this assignment']);
        return;
    }
    
    // Escape notes
    $notes = $conn->real_escape_string($notes);
    
    // Update based on user type
    if ($user_type === 'admin') {
        // Admin updates admin_status
        $query = "UPDATE staff_assignments SET admin_status = '$new_status', staff_notes = '$notes' WHERE id = $assignment_id";
    } else {
        // Staff updates staff_status and can add notes
        $query = "UPDATE staff_assignments SET staff_status = '$new_status', staff_notes = '$notes' WHERE id = $assignment_id";
    }
    
    if ($conn->query($query)) {
        // Check if both have confirmed
        $result = $conn->query("SELECT admin_status, staff_status FROM staff_assignments WHERE id = $assignment_id");
        $updated = $result->fetch_assoc();
        
        // Determine final status
        $final_status = 'pending';
        if ($updated['admin_status'] === 'completed' && $updated['staff_status'] === 'completed') {
            $final_status = 'completed';
        } elseif ($updated['admin_status'] === 'in_progress' || $updated['staff_status'] === 'in_progress') {
            $final_status = 'in_progress';
        } elseif ($updated['admin_status'] === 'rejected' || $updated['staff_status'] === 'rejected') {
            $final_status = 'rejected';
        }
        
        // Update main status
        $conn->query("UPDATE staff_assignments SET status = '$final_status' WHERE id = $assignment_id");
        
        echo json_encode(['success' => true, 'message' => 'Status updated successfully', 'final_status' => $final_status]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating status']);
    }
}

function deleteTaskAssignment() {
    global $conn;
    
    // Verify admin is logged in
    if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $assignment_id = isset($_POST['assignment_id']) ? intval($_POST['assignment_id']) : 0;
    
    if (!$assignment_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid assignment ID']);
        return;
    }
    
    // Verify the assignment belongs to this admin
    $query = "SELECT admin_id FROM staff_assignments WHERE id = $assignment_id";
    $result = $conn->query($query);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Assignment not found']);
        return;
    }
    
    $assignment = $result->fetch_assoc();
    if ($assignment['admin_id'] !== $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }
    
    $query = "DELETE FROM staff_assignments WHERE id = $assignment_id";
    
    if ($conn->query($query)) {
        echo json_encode(['success' => true, 'message' => 'Assignment deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting assignment']);
    }
}

// TEST FUNCTIONS FOR DEBUGGING TESTIMONIALS
function testReviewsTable() {
    global $conn;
    
    $check_query = "SHOW TABLES LIKE 'reviews'";
    $result = $conn->query($check_query);
    
    if ($result && $result->num_rows > 0) {
        echo json_encode(['success' => true, 'message' => 'Reviews table exists']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Reviews table does not exist']);
    }
}

function testApprovedCount() {
    global $conn;
    
    $query = "SELECT COUNT(*) as count FROM reviews WHERE status = 'approved'";
    $result = $conn->query($query);
    
    if ($result) {
        $row = $result->fetch_assoc();
        echo json_encode(['success' => true, 'data' => $row]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error']);
    }
}

function testAllReviews() {
    global $conn;
    
    $approved_query = "SELECT COUNT(*) as count FROM reviews WHERE status = 'approved'";
    $pending_query = "SELECT COUNT(*) as count FROM reviews WHERE status = 'pending'";
    $all_query = "SELECT COUNT(*) as count FROM reviews";
    $reviews_query = "SELECT r.*, u.name as customer_name FROM reviews r LEFT JOIN users u ON r.user_id = u.id ORDER BY r.created_at DESC LIMIT 10";
    
    $approved = $conn->query($approved_query)->fetch_assoc()['count'];
    $pending = $conn->query($pending_query)->fetch_assoc()['count'];
    $total = $conn->query($all_query)->fetch_assoc()['count'];
    $reviews = [];
    
    $result = $conn->query($reviews_query);
    while ($row = $result->fetch_assoc()) {
        $reviews[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => [
            'total' => $total,
            'approved' => $approved,
            'pending' => $pending,
            'reviews' => $reviews
        ]
    ]);
}
?>
