<?php
// ajax/restore_batch.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$batch_id = $_POST['batch_id'] ?? 0;
$reason = trim($_POST['reason'] ?? '');

if ($batch_id <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid batch ID']);
    exit;
}

try {
    // Check if batch exists and is inactive
    $stmt = $pdo->prepare("SELECT id, batch_no, is_active FROM product_batches WHERE id = ?");
    $stmt->execute([$batch_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        echo json_encode(['status' => 'error', 'message' => 'Batch not found']);
        exit;
    }
    
    if ($batch['is_active'] == 1) {
        echo json_encode(['status' => 'error', 'message' => 'Batch is already active']);
        exit;
    }
    
    // Reactivate the batch
    $stmt = $pdo->prepare("UPDATE product_batches SET is_active = 1 WHERE id = ?");
    $stmt->execute([$batch_id]);
    
    // Log the restoration if reason provided
    if (!empty($reason)) {
        $stmt = $pdo->prepare("INSERT INTO audit_log (user_id, action, details, created_at) 
                              VALUES (?, ?, ?, NOW())");
        $stmt->execute([
            $_SESSION['user']['id'],
            'BATCH_RESTORE',
            "Batch #{$batch_id} ({$batch['batch_no']}) restored. Reason: $reason"
        ]);
    }
    
    echo json_encode([
        'status' => 'success', 
        'message' => "Batch {$batch['batch_no']} has been restored"
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>