<?php
session_start();
include '../layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Set headers for JSON response
header('Content-Type: application/json');

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input provided');
    }
    
    $action = $input['action'] ?? '';
    $customerIds = $input['customer_ids'] ?? [];
    $userId = $_SESSION['user_id'];
    
    // Validate input
    if (empty($action)) {
        throw new Exception('Action is required');
    }
    
    if (empty($customerIds) || !is_array($customerIds)) {
        throw new Exception('Customer IDs array is required');
    }
    
    // Sanitize customer IDs
    $customerIds = array_map('intval', $customerIds);
    $customerIds = array_filter($customerIds, function($id) { return $id > 0; });
    
    if (empty($customerIds)) {
        throw new Exception('No valid customer IDs provided');
    }
    
    // Validate action
    $allowedActions = ['activate', 'deactivate', 'suspend', 'export', 'delete'];
    if (!in_array($action, $allowedActions)) {
        throw new Exception('Invalid action specified');
    }
    
    // Check user permissions (you might want to add role-based checks here)
    $userRoleQuery = "SELECT ur.role_name FROM users u 
                      INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                      WHERE u.user_id = ?";
    $stmt = $conn->prepare($userRoleQuery);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $userRole = $stmt->get_result()->fetch_assoc()['role_name'] ?? 'Guest';
    
    // Some actions might be restricted to certain roles
    if ($action === 'delete' && !in_array($userRole, ['Administrator', 'Operations Manager'])) {
        throw new Exception('You do not have permission to delete customers');
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    $successCount = 0;
    $errors = [];
    $processedCustomers = [];
    
    try {
        // Create placeholders for IN clause
        $placeholders = str_repeat('?,', count($customerIds) - 1) . '?';
        
        // Get customer details for logging
        $customerQuery = "SELECT customer_id, customer_code, 
                                 CASE 
                                     WHEN customer_type = 'CORPORATE' THEN company_name 
                                     ELSE CONCAT(first_name, ' ', last_name) 
                                 END as customer_name,
                                 status, customer_type
                          FROM customers 
                          WHERE customer_id IN ($placeholders)";
        
        $stmt = $conn->prepare($customerQuery);
        $stmt->bind_param(str_repeat('i', count($customerIds)), ...$customerIds);
        $stmt->execute();
        $customers = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        if (empty($customers)) {
            throw new Exception('No valid customers found with the provided IDs');
        }
        
        // Process each action
        switch ($action) {
            case 'activate':
                $updateQuery = "UPDATE customers 
                               SET status = 'ACTIVE', updated_at = CURRENT_TIMESTAMP 
                               WHERE customer_id IN ($placeholders) AND status != 'ACTIVE'";
                break;
                
            case 'deactivate':
                $updateQuery = "UPDATE customers 
                               SET status = 'INACTIVE', updated_at = CURRENT_TIMESTAMP 
                               WHERE customer_id IN ($placeholders) AND status != 'INACTIVE'";
                break;
                
            case 'suspend':
                $updateQuery = "UPDATE customers 
                               SET status = 'SUSPENDED', updated_at = CURRENT_TIMESTAMP 
                               WHERE customer_id IN ($placeholders) AND status != 'SUSPENDED'";
                break;
                
            case 'export':
                // For export, we'll return the customer data
                $response = [
                    'success' => true,
                    'message' => 'Customer data prepared for export',
                    'data' => $customers,
                    'action' => 'export',
                    'count' => count($customers)
                ];
                
                echo json_encode($response);
                return;
                
            case 'delete':
                // Check if customers have shipments before deletion
                $shipmentCheckQuery = "SELECT DISTINCT sender_customer_id 
                                      FROM shipments 
                                      WHERE sender_customer_id IN ($placeholders)";
                $stmt = $conn->prepare($shipmentCheckQuery);
                $stmt->bind_param(str_repeat('i', count($customerIds)), ...$customerIds);
                $stmt->execute();
                $customersWithShipments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
                
                if (!empty($customersWithShipments)) {
                    $customerIdsWithShipments = array_column($customersWithShipments, 'sender_customer_id');
                    throw new Exception('Cannot delete customers with existing shipments. Customer IDs: ' . implode(', ', $customerIdsWithShipments));
                }
                
                $updateQuery = "DELETE FROM customers WHERE customer_id IN ($placeholders)";
                break;
                
            default:
                throw new Exception('Unsupported bulk action');
        }
        
        // Execute the update query
        $stmt = $conn->prepare($updateQuery);
        $stmt->bind_param(str_repeat('i', count($customerIds)), ...$customerIds);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to execute bulk action: ' . $stmt->error);
        }
        
        $affectedRows = $stmt->affected_rows;
        
        if ($affectedRows === 0 && $action !== 'delete') {
            // This might happen if all customers are already in the target state
            $message = "No customers were updated. They may already be in the requested state.";
        } else {
            $successCount = $affectedRows;
            
            // Log each customer action
            foreach ($customers as $customer) {
                if ($action === 'delete' || 
                    ($action === 'activate' && $customer['status'] !== 'ACTIVE') ||
                    ($action === 'deactivate' && $customer['status'] !== 'INACTIVE') ||
                    ($action === 'suspend' && $customer['status'] !== 'SUSPENDED')) {
                    
                    // Log the activity
                    $logQuery = "INSERT INTO activity_log 
                                (user_id, action, module, record_id, old_values, new_values, ip_address, logged_at) 
                                VALUES (?, 'BULK_UPDATE', 'customers', ?, ?, ?, ?, NOW())";
                    
                    $stmt = $conn->prepare($logQuery);
                    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                    $oldValues = json_encode(['status' => $customer['status']]);
                    $newValues = json_encode(['status' => $action === 'delete' ? 'DELETED' : strtoupper($action === 'activate' ? 'ACTIVE' : ($action === 'deactivate' ? 'INACTIVE' : 'SUSPENDED'))]);
                    
                    $stmt->bind_param("issss", $userId, $customer['customer_id'], $oldValues, $newValues, $ipAddress);
                    $stmt->execute();
                    
                    $processedCustomers[] = [
                        'id' => $customer['customer_id'],
                        'code' => $customer['customer_code'],
                        'name' => $customer['customer_name'],
                        'old_status' => $customer['status'],
                        'new_status' => $action === 'delete' ? 'DELETED' : strtoupper($action === 'activate' ? 'ACTIVE' : ($action === 'deactivate' ? 'INACTIVE' : 'SUSPENDED'))
                    ];
                }
            }
            
            $message = "Successfully processed $successCount customers";
        }
        
        // Commit transaction
        $conn->commit();
        
        // Prepare success response
        $response = [
            'success' => true,
            'message' => $message,
            'data' => [
                'action' => $action,
                'requested_count' => count($customerIds),
                'processed_count' => $successCount,
                'customers' => $processedCustomers,
                'executed_by' => $userId,
                'executed_at' => date('Y-m-d H:i:s')
            ]
        ];
        
        echo json_encode($response);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    // Log error for debugging
    error_log("Bulk Customer Actions Error: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    
    // Return error response
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'debug_info' => [
            'action' => $action ?? 'unknown',
            'customer_count' => count($customerIds ?? []),
            'user_id' => $userId ?? 'unknown',
            'timestamp' => date('Y-m-d H:i:s')
        ]
    ]);
} finally {
    // Close database connection
    if (isset($conn)) {
        $conn->close();
    }
}
?>