<?php
/**
 * Badge Print Tracking API
 * Handles marking badges as printed/unprinted
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login and delegates edit permission
requirePermission('delegates', 'edit');

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

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    $pdo = getDBConnection();
    
    switch ($action) {
        case 'mark_printed':
            markBadgesAsPrinted($pdo);
            break;
            
        case 'mark_unprinted':
            markBadgesAsUnprinted($pdo);
            break;
            
        case 'toggle_print_status':
            togglePrintStatus($pdo);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

/**
 * Mark one or more badges as printed
 */
function markBadgesAsPrinted($pdo) {
    $delegate_ids = $_POST['delegate_ids'] ?? '';
    
    if (empty($delegate_ids)) {
        echo json_encode(['success' => false, 'error' => 'No delegates specified']);
        return;
    }
    
    // Convert to array if comma-separated string
    if (is_string($delegate_ids)) {
        $delegate_ids = array_filter(array_map('intval', explode(',', $delegate_ids)));
    }
    
    if (empty($delegate_ids)) {
        echo json_encode(['success' => false, 'error' => 'Invalid delegate IDs']);
        return;
    }
    
    // Get admin user ID from session (if available)
    $admin_id = $_SESSION['admin_id'] ?? null;
    
    // For each delegate, find their most recent badge generation log entry and mark it as printed
    $updated_count = 0;
    
    foreach ($delegate_ids as $delegate_id) {
        // First check if there's a badge generation log entry
        $check_stmt = $pdo->prepare("
            SELECT id FROM badge_generation_log 
            WHERE delegate_id = ? 
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        $check_stmt->execute([$delegate_id]);
        $log_entry = $check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($log_entry) {
            // Update existing log entry
            $stmt = $pdo->prepare("
                UPDATE badge_generation_log 
                SET is_printed = 1, 
                    printed_at = CURRENT_TIMESTAMP,
                    printed_by = ?
                WHERE id = ?
            ");
            $stmt->execute([$admin_id, $log_entry['id']]);
            $updated_count++;
        } else {
            // Create a new log entry if none exists (delegate has badge but no log)
            $stmt = $pdo->prepare("
                INSERT INTO badge_generation_log 
                (delegate_id, generation_type, is_printed, printed_at, printed_by, created_at) 
                VALUES (?, 'single', 1, CURRENT_TIMESTAMP, ?, CURRENT_TIMESTAMP)
            ");
            $stmt->execute([$delegate_id, $admin_id]);
            $updated_count++;
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Marked {$updated_count} badge(s) as printed",
        'updated_count' => $updated_count
    ]);
}

/**
 * Mark one or more badges as unprinted
 */
function markBadgesAsUnprinted($pdo) {
    $delegate_ids = $_POST['delegate_ids'] ?? '';
    
    if (empty($delegate_ids)) {
        echo json_encode(['success' => false, 'error' => 'No delegates specified']);
        return;
    }
    
    // Convert to array if comma-separated string
    if (is_string($delegate_ids)) {
        $delegate_ids = array_filter(array_map('intval', explode(',', $delegate_ids)));
    }
    
    if (empty($delegate_ids)) {
        echo json_encode(['success' => false, 'error' => 'Invalid delegate IDs']);
        return;
    }
    
    // Update the most recent badge generation log entry for each delegate
    $updated_count = 0;
    
    foreach ($delegate_ids as $delegate_id) {
        // First get the latest log entry ID
        $get_latest_stmt = $pdo->prepare("
            SELECT id FROM badge_generation_log 
            WHERE delegate_id = ? 
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        $get_latest_stmt->execute([$delegate_id]);
        $latest_entry = $get_latest_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($latest_entry) {
            // Update the latest entry
            $stmt = $pdo->prepare("
                UPDATE badge_generation_log 
                SET is_printed = 0, 
                    printed_at = NULL,
                    printed_by = NULL
                WHERE id = ?
            ");
            $stmt->execute([$latest_entry['id']]);
            
            if ($stmt->rowCount() > 0) {
                $updated_count++;
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Marked {$updated_count} badge(s) as unprinted",
        'updated_count' => $updated_count
    ]);
}

/**
 * Toggle print status for a single badge
 */
function togglePrintStatus($pdo) {
    $delegate_id = $_POST['delegate_id'] ?? 0;
    
    if (empty($delegate_id)) {
        echo json_encode(['success' => false, 'error' => 'No delegate specified']);
        return;
    }
    
    $admin_id = $_SESSION['admin_id'] ?? null;
    
    // Get current print status
    $stmt = $pdo->prepare("
        SELECT id, is_printed 
        FROM badge_generation_log 
        WHERE delegate_id = ? 
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$delegate_id]);
    $log_entry = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($log_entry) {
        // Toggle the status
        $new_status = !$log_entry['is_printed'];
        
        $update_stmt = $pdo->prepare("
            UPDATE badge_generation_log 
            SET is_printed = ?,
                printed_at = " . ($new_status ? "CURRENT_TIMESTAMP" : "NULL") . ",
                printed_by = ?
            WHERE id = ?
        ");
        $update_stmt->execute([
            $new_status ? 1 : 0, 
            $new_status ? $admin_id : null, 
            $log_entry['id']
        ]);
        
        echo json_encode([
            'success' => true,
            'is_printed' => $new_status,
            'message' => $new_status ? 'Badge marked as printed' : 'Badge marked as unprinted'
        ]);
    } else {
        // Create new log entry as printed
        $insert_stmt = $pdo->prepare("
            INSERT INTO badge_generation_log 
            (delegate_id, generation_type, is_printed, printed_at, printed_by, created_at) 
            VALUES (?, 'single', TRUE, CURRENT_TIMESTAMP, ?, CURRENT_TIMESTAMP)
        ");
        $insert_stmt->execute([$delegate_id, $admin_id]);
        
        echo json_encode([
            'success' => true,
            'is_printed' => true,
            'message' => 'Badge marked as printed'
        ]);
    }
}

