<?php

session_start();
require_once "../config/connection.php";
require_once "approval_functions.php";

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

// Check if user is admin
if (!is_logged_in() || !is_user_type('admin')) {
    echo json_encode(generateResponse('error', 'Unauthorized access'));
    exit();
}

// Check if action is provided
if (!isset($_POST['action'])) {
    echo json_encode(generateResponse('error', 'No action specified'));
    exit();
}

$admin_id = $_SESSION['user_id'];
$action = $_POST['action'];
$item_id = isset($_POST['item_id']) ? intval($_POST['item_id']) : 0;
$transaction_id = isset($_POST['transaction_id']) ? intval($_POST['transaction_id']) : 0;

// Validate required parameters
if ($item_id === 0 || $transaction_id === 0) {
    echo json_encode(generateResponse('error', 'Invalid parameters'));
    exit();
}

// Get the transaction item data with related information
$stmt = $conn->prepare("
    SELECT ti.*, csi.component_id, csi.color_id, cpc.available_quantity, st.borrower_id,
           st.tanggal_transaksi, st.expected_duration, st.duration_type, bu.lokasi_posisi
    FROM transaction_items_surabaya ti 
    JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
    JOIN color_panel_components_surabaya cpc ON csi.color_id = cpc.color_id AND csi.component_id = cpc.component_id
    JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id
    JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
    WHERE ti.id = ?
");
$stmt->bind_param("i", $item_id);
$stmt->execute();
$item_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$item_data) {
    echo json_encode(generateResponse('error', 'Item tidak ditemukan'));
    exit();
}

// Begin transaction
$conn->begin_transaction();

try {
    switch ($action) {
        case 'approve':
            handleApprove($conn, $item_id, $transaction_id, $item_data, $admin_id);
            break;
            
        case 'reject':
            handleReject($conn, $item_id, $transaction_id, $_POST['note'] ?? '', $admin_id);
            break;
            
        case 'onprocess':
            handleOnProcess($conn, $item_id, $transaction_id, $item_data, $admin_id);
            break;
            
        case 'return':
            handleReturn($conn, $item_id, $transaction_id, $item_data, $_POST['condition'] ?? 'Baik', $_POST['note'] ?? '', $admin_id);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
    // Commit transaction
    $conn->commit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    echo json_encode(generateResponse('error', 'Terjadi kesalahan: ' . $e->getMessage()));
    exit();
}

/**
 * Handle approve action
 */
function handleApprove($conn, $item_id, $transaction_id, $item_data, $admin_id) {
    // Check if there's enough available quantity
    if ($item_data['available_quantity'] < 1) {
        throw new Exception('Stok tidak mencukupi');
    }
    
    // Update the item status to approved with status_waktu = 'none' (dipinjam)
    $quantity_approved = 1;
    $stmt = $conn->prepare("UPDATE transaction_items_surabaya SET quantity_approved = ?, status_waktu = 'none' WHERE id = ?");
    $stmt->bind_param("ii", $quantity_approved, $item_id);
    $stmt->execute();
    $stmt->close();
    
    // Reduce the available quantity
    $new_quantity = $item_data['available_quantity'] - $quantity_approved;
    updateAvailableQuantity($conn, $item_data['color_id'], $item_data['component_id'], $new_quantity);
    
    // Update the transaction status
    updateTransactionStatus($conn, $transaction_id);
    
    // Update item location to borrower's location
    $lokasi_tujuan = $item_data['lokasi_tujuan'] ?: $item_data['lokasi_posisi'];
    $stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET status = 'Dipinjam', lokasi = ? WHERE id = ?");
    $stmt->bind_param("si", $lokasi_tujuan, $item_data['stock_item_id']);
    $stmt->execute();
    $stmt->close();
    
    // Log activity
    log_activity($conn, $admin_id, 'admin', 'Approve Item', "Admin approved item ID: {$item_id} for transaction {$transaction_id}");
    
    echo json_encode(generateResponse('success', 'Item berhasil disetujui'));
}

/**
 * Handle reject action
 */
function handleReject($conn, $item_id, $transaction_id, $note, $admin_id) {
    // Update the item status to rejected
    $stmt = $conn->prepare("UPDATE transaction_items_surabaya SET quantity_approved = 0, catatan = ? WHERE id = ?");
    $stmt->bind_param("si", $note, $item_id);
    $stmt->execute();
    $stmt->close();
    
    // Update the transaction status
    updateTransactionStatus($conn, $transaction_id);
    
    // Log activity
    log_activity($conn, $admin_id, 'admin', 'Reject Item', "Admin rejected item ID: {$item_id} for transaction {$transaction_id}. Note: {$note}");
    
    echo json_encode(generateResponse('success', 'Item berhasil ditolak'));
}

/**
 * Handle on process action
 */
function handleOnProcess($conn, $item_id, $transaction_id, $item_data, $admin_id) {
    // Get borrower data for automated message
    $stmt = $conn->prepare("SELECT bu.username FROM borrower_users_surabaya bu JOIN stock_transactions_surabaya st ON bu.id = st.borrower_id WHERE st.id = ?");
    $stmt->bind_param("i", $transaction_id);
    $stmt->execute();
    $borrower_data = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // Calculate expected return date
    $transaction_date = new DateTime($item_data['tanggal_transaksi']);
    if ($item_data['duration_type'] === 'hours') {
        $return_date = clone $transaction_date;
        $return_date->add(new DateInterval('PT' . $item_data['expected_duration'] . 'H'));
        $return_date_str = $return_date->format('d M Y H:i');
    } else {
        $return_date = clone $transaction_date;
        $return_date->add(new DateInterval('P' . $item_data['expected_duration'] . 'D'));
        $return_date_str = $return_date->format('d M Y');
    }
    
    $automated_note = "Item sedang dipinjam oleh {$borrower_data['username']} mulai tanggal " . 
                      date('d M Y H:i', strtotime($item_data['tanggal_transaksi'])) . 
                      " sampai {$return_date_str}. Silakan tunggu hingga item dikembalikan.";
    
    // Update the transaction item status
    $stmt = $conn->prepare("UPDATE transaction_items_surabaya SET catatan = ? WHERE id = ?");
    $stmt->bind_param("si", $automated_note, $item_id);
    $stmt->execute();
    $stmt->close();
    
    // Update the transaction status
    $stmt = $conn->prepare("UPDATE stock_transactions_surabaya SET status = 'OnProccesing', catatan_proses = ? WHERE id = ?");
    $stmt->bind_param("si", $automated_note, $transaction_id);
    $stmt->execute();
    $stmt->close();
    
    // Log activity
    log_activity($conn, $admin_id, 'admin', 'Process Item', "Admin set item ID: {$item_id} to OnProcessing for transaction {$transaction_id}");
    
    echo json_encode(generateResponse('success', 'Item berhasil diproses'));
}

/**
 * Handle return action
 */
function handleReturn($conn, $item_id, $transaction_id, $item_data, $condition, $note, $admin_id) {
    // Calculate time status based on return time
    $time_status = calculateReturnTimeStatus($item_data);
    
    // Update the item status to returned with time status
    $stmt = $conn->prepare("
        UPDATE transaction_items_surabaya 
        SET dikembalikan = 1, 
            tanggal_kembali = NOW(), 
            kondisi_kembali = ?, 
            catatan = ?,
            status_waktu = ?
        WHERE id = ?
    ");
    $stmt->bind_param("sssi", $condition, $note, $time_status, $item_id);
    $stmt->execute();
    $stmt->close();
    
    // If the condition is 'Baik', restore the available quantity
    if ($condition === 'Baik') {
        $new_quantity = $item_data['available_quantity'] + ($item_data['quantity_approved'] ?? 1);
        updateAvailableQuantity($conn, $item_data['color_id'], $item_data['component_id'], $new_quantity);
        $new_item_status = 'Tersedia';
    } else {
        // For 'Rusak' or 'Hilang', don't restore quantity
        $new_item_status = $condition;
    }
    
    // Update the item location back to Color Room and status
    $stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET status = ?, lokasi = 'Color Room' WHERE id = ?");
    $stmt->bind_param("si", $new_item_status, $item_data['stock_item_id']);
    $stmt->execute();
    $stmt->close();
    
    // Check if all items are returned and update transaction status
    $stmt = $conn->prepare("
        SELECT COUNT(*) as total, SUM(dikembalikan) as returned 
        FROM transaction_items_surabaya 
        WHERE transaction_id = ? AND quantity_approved > 0
    ");
    $stmt->bind_param("i", $transaction_id);
    $stmt->execute();
    $return_status = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if ($return_status['total'] == $return_status['returned']) {
        $stmt = $conn->prepare("
            UPDATE stock_transactions_surabaya 
            SET status_peminjaman = 'Dikembalikan',
                tanggal_pengembalian = NOW(),
                catatan_pengembalian = ? 
            WHERE id = ?
        ");
        $stmt->bind_param("si", $note, $transaction_id);
        $stmt->execute();
        $stmt->close();
    }
    
    // Log activity with time status information
    $time_status_text = $time_status === 'tepat' ? 'tepat waktu' : ($time_status === 'overdue' ? 'terlambat' : 'dipinjam');
    log_activity($conn, $admin_id, 'admin', 'Return Item', 
                "Admin processed return for item ID: {$item_id}, condition: {$condition}, time status: {$time_status_text}");
    
    $response_message = "Item berhasil dikembalikan";
    if ($time_status === 'overdue') {
        $response_message .= " (terlambat)";
    } elseif ($time_status === 'tepat') {
        $response_message .= " (tepat waktu)";
    }
    
    echo json_encode(generateResponse('success', $response_message));
}
?>