<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Set timezone to Indonesia (WIB/WITA/WIT - adjust according to your location)
date_default_timezone_set('Asia/Jakarta');

// Function to send JSON response with mobile optimization
function sendJSONResponse($success, $message, $data = null) {
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    
    // Detect mobile device
    $isMobile = isset($_SERVER['HTTP_USER_AGENT']) && 
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false || 
                 strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false ||
                 strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false);
    
    // Optimize message for mobile
    if ($isMobile && !$success && strlen($message) > 200) {
        $message = substr($message, 0, 197) . '...';
    }
    
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'mobile' => $isMobile
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        sendJSONResponse(false, 'Akses tidak diizinkan');
    } else {
        header("Location: ../login.php");
        exit();
    }
}

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: formulir_isi_peminjam.php");
    exit();
}

// Get borrower data
$borrower_id = $_SESSION['user_id'];

// Validate required fields
$required_fields = [
    'tanggal_transaksi_date', 'tanggal_transaksi_time', 
    'tanggal_pengembalian_date', 'tanggal_pengembalian_time', 
    'cart_items'
];

foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        sendJSONResponse(false, "Field {$field} harus diisi");
    }
}

// Decode cart items
$cart_items = json_decode($_POST['cart_items'], true);

// Check if cart is empty
if (empty($cart_items)) {
    sendJSONResponse(false, "Pilih minimal satu item untuk dipinjam");
}

// Validate cart items structure
foreach ($cart_items as $index => $item) {
    $required_item_fields = ['id', 'kode_barang', 'component_name', 'status'];
    foreach ($required_item_fields as $field) {
        if (!isset($item[$field]) || empty($item[$field])) {
            sendJSONResponse(false, "Data item ke-" . ($index + 1) . " tidak lengkap");
        }
    }
}

// Get form data
$tanggal_transaksi_date = mysqli_real_escape_string($conn, $_POST['tanggal_transaksi_date']);
$tanggal_transaksi_time = mysqli_real_escape_string($conn, $_POST['tanggal_transaksi_time']);
$tanggal_pengembalian_date = mysqli_real_escape_string($conn, $_POST['tanggal_pengembalian_date']);
$tanggal_pengembalian_time = mysqli_real_escape_string($conn, $_POST['tanggal_pengembalian_time']);
$keterangan = isset($_POST['keterangan']) ? mysqli_real_escape_string($conn, $_POST['keterangan']) : '';

// Combine date and time into datetime format
$tanggal_transaksi = $tanggal_transaksi_date . ' ' . $tanggal_transaksi_time . ':00';
$tanggal_pengembalian = $tanggal_pengembalian_date . ' ' . $tanggal_pengembalian_time . ':00';

// Create timezone object for Indonesia
$timezone = new DateTimeZone('Asia/Jakarta');

// Validate transaction date (cannot be in the past)
try {
    $transaction_datetime = new DateTime($tanggal_transaksi, $timezone);
    $current_datetime = new DateTime('now', $timezone);
    
    // Allow some tolerance (5 minutes) for slight time differences
    $current_with_tolerance = clone $current_datetime;
    $current_with_tolerance->sub(new DateInterval('PT5M'));
    
    if ($transaction_datetime < $current_with_tolerance) {
        $current_time_display = $current_datetime->format('d-m-Y H:i:s');
        sendJSONResponse(false, "Waktu transaksi tidak boleh di masa lalu. Waktu saat ini: {$current_time_display}");
    }
} catch (Exception $e) {
    sendJSONResponse(false, "Format tanggal/waktu tidak valid: " . $e->getMessage());
}

// Validate return date
try {
    $return_datetime = new DateTime($tanggal_pengembalian, $timezone);
} catch (Exception $e) {
    sendJSONResponse(false, "Format tanggal/waktu pengembalian tidak valid: " . $e->getMessage());
}

// Basic validation: return date should be after transaction date
if ($return_datetime <= $transaction_datetime) {
    sendJSONResponse(false, "Waktu pengembalian harus setelah waktu transaksi");
}

// Optional validation: check if return date is reasonable (not too far in the future)
$max_allowed_date = clone $transaction_datetime;
$max_allowed_date->add(new DateInterval('P30D')); // Maximum 30 days

if ($return_datetime > $max_allowed_date) {
    sendJSONResponse(false, "Waktu pengembalian maksimal 30 hari dari waktu transaksi");
}

// Calculate duration for display purposes
$duration_seconds = $return_datetime->getTimestamp() - $transaction_datetime->getTimestamp();
$duration_hours = $duration_seconds / 3600;

// Format duration for display
if ($duration_hours < 24) {
    $duration_display = number_format($duration_hours, 1) . ' jam';
} else {
    $duration_days = $duration_hours / 24;
    $duration_display = number_format($duration_days, 1) . ' hari';
}

// Generate reservation number
function generateReservationNumber($conn) {
    // Get current week number and year (with timezone)
    $now = new DateTime('now', new DateTimeZone('Asia/Jakarta'));
    $weekNumber = $now->format('W');
    $year = $now->format('y');
    
    // Find the last reservation number for this week and year
    $query = "SELECT reservation_number FROM stock_transactions 
              WHERE reservation_number LIKE 'Resv/{$weekNumber}/{$year}/%' 
              ORDER BY reservation_number DESC LIMIT 1";
    
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $lastNumber = $result->fetch_assoc()['reservation_number'];
        // Extract the sequence number
        $sequence = (int)substr($lastNumber, -3);
        $sequence++;
    } else {
        $sequence = 1;
    }
    
    // Format the new reservation number
    $reservationNumber = "Resv/{$weekNumber}/{$year}/" . str_pad($sequence, 3, '0', STR_PAD_LEFT);
    
    return $reservationNumber;
}

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

try {
    // Get borrower location
    $stmt = $conn->prepare("SELECT lokasi_posisi FROM borrower_users WHERE id = ?");
    $stmt->bind_param("i", $borrower_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception("Data borrower tidak ditemukan");
    }
    
    $borrower_data = $result->fetch_assoc();
    $lokasi_tujuan = $borrower_data['lokasi_posisi'];
    $stmt->close();
    
    // Validate location
    $valid_locations = ['PTG 6', 'PTG MANUAL', 'PACKING', 'CHAIR', 'QC OPEN BOX', 'PTG 6 CONVEYOR','PUSHPULL MANUAL'];
    if (!in_array($lokasi_tujuan, $valid_locations)) {
        throw new Exception("Lokasi posisi tidak valid: " . $lokasi_tujuan);
    }
    
    // Validate all items exist and are available for borrowing
    $validated_items = [];
    foreach ($cart_items as $item) {
        $item_id = (int)$item['id'];
        
        // Check if item still exists and get current status
        $check_stmt = $conn->prepare("
            SELECT csi.id, csi.kode_barang, csi.status, csi.color_id, csi.component_id,
                   cc.component_name, mcp.code_color, b.nama_buyer
            FROM color_stock_items csi
            JOIN color_components cc ON csi.component_id = cc.id
            JOIN master_color_panel mcp ON csi.color_id = mcp.id
            JOIN buyers b ON mcp.buyer_id = b.id
            WHERE csi.id = ?
        ");
        $check_stmt->bind_param("i", $item_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows === 0) {
            $check_stmt->close();
            throw new Exception("Item {$item['kode_barang']} tidak ditemukan");
        }
        
        $current_item = $check_result->fetch_assoc();
        $check_stmt->close();
        
        // Check if item status allows borrowing - STRICT validation including 'Dipinjam'
        $restricted_statuses = ['Expired', 'Hilang', 'Dipinjam'];
        if (in_array($current_item['status'], $restricted_statuses)) {
            if ($current_item['status'] === 'Dipinjam') {
                throw new Exception("Item {$current_item['kode_barang']} sedang dipinjam dan tidak dapat dipinjam kembali");
            } else {
                throw new Exception("Item {$current_item['kode_barang']} tidak dapat dipinjam (Status: {$current_item['status']})");
            }
        }
        
        $validated_items[] = $current_item;
    }
    
    // Generate reservation number
    $reservationNumber = generateReservationNumber($conn);
    
    // Format datetime for MySQL
    $mysql_tanggal_transaksi = $transaction_datetime->format('Y-m-d H:i:s');
    $mysql_tanggal_pengembalian = $return_datetime->format('Y-m-d H:i:s');
    
    // Create a single transaction for all items
    $stmt = $conn->prepare("
        INSERT INTO stock_transactions (
            reservation_number, borrower_id, tanggal_transaksi, tanggal_pengembalian, 
            status, keterangan, status_peminjaman, collection_id
        ) VALUES (?, ?, ?, ?, 'Disetujui', ?, 'Dipinjam', NULL)
    ");
    
    $stmt->bind_param(
        "sisss", 
        $reservationNumber, $borrower_id, $mysql_tanggal_transaksi, $mysql_tanggal_pengembalian, $keterangan
    );
    $stmt->execute();
    $transaction_id = $conn->insert_id;
    $stmt->close();
    
    // Insert transaction items and update item statuses
    $stmt = $conn->prepare("
        INSERT INTO transaction_items (
            transaction_id, stock_item_id, 
            lokasi_asal, lokasi_tujuan, 
            quantity_requested, quantity_approved, dikembalikan, status_waktu
        ) VALUES (?, ?, 'Color Room', ?, 1, 1, 0, 'none')
    ");
    
    // Prepare statements for updating item status and available quantity
    $update_item_stmt = $conn->prepare("UPDATE color_stock_items SET status = 'Dipinjam' WHERE id = ?");
    $update_quantity_stmt = $conn->prepare("
        UPDATE color_panel_components 
        SET available_quantity = GREATEST(0, available_quantity - 1)
        WHERE color_id = ? AND component_id = ?
    ");
    
    foreach ($validated_items as $item) {
        $item_id = $item['id'];
        $color_id = $item['color_id'];
        $component_id = $item['component_id'];
        
        // Insert transaction item
        $stmt->bind_param("iis", $transaction_id, $item_id, $lokasi_tujuan);
        $stmt->execute();
        
        // Update item status to 'Dipinjam'
        $update_item_stmt->bind_param("i", $item_id);
        $update_item_stmt->execute();
        
        // Decrease available quantity in color_panel_components
        $update_quantity_stmt->bind_param("ii", $color_id, $component_id);
        $update_quantity_stmt->execute();
    }
    
    $stmt->close();
    $update_item_stmt->close();
    $update_quantity_stmt->close();
    
    // Log activity for the transaction
    log_activity($conn, $borrower_id, 'borrower', 'Peminjaman Diproses', 
        "borrower berhasil meminjam " . count($validated_items) . " item dengan reservasi {$reservationNumber}");
    
    // Log to audit_logs for successful submission
    $log_details = "borrower ID: $borrower_id berhasil memproses peminjaman dengan ID: $transaction_id untuk " . count($validated_items) . " item (Durasi: $duration_display) - Status langsung Dipinjam";
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_type = 'borrower';
    $action_type = 'Submit Peminjaman';
    $stmt = $conn->prepare("INSERT INTO audit_logs (user_id, user_type, action_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("issss", $borrower_id, $user_type, $action_type, $log_details, $ip_address);
    $stmt->execute();
    $stmt->close();
    
    // Commit transaction
    $conn->commit();
    
    // Detect mobile for response optimization
    $isMobile = isset($_SERVER['HTTP_USER_AGENT']) && 
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false || 
                 strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false ||
                 strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false);
    
    // Prepare success message (mobile-optimized)
    if ($isMobile) {
        $success_message = "✅ Peminjaman berhasil!<br>" . 
                          "<strong>No. Reservasi:</strong> {$reservationNumber}<br>" . 
                          "<strong>Item:</strong> " . count($validated_items) . " item<br>" . 
                          "<strong>Durasi:</strong> {$duration_display}<br>" . 
                          "<strong>Lokasi:</strong> {$lokasi_tujuan}<br>" . 
                          "<strong>Status:</strong> Dipinjam";
    } else {
        $success_message = "Peminjaman berhasil diproses dengan nomor reservasi <strong>" . $reservationNumber . "</strong> untuk " . count($validated_items) . " item dengan durasi " . $duration_display . " ke lokasi <strong>" . $lokasi_tujuan . "</strong>. Status: <strong>Dipinjam</strong> (langsung disetujui).";
    }
    
    // Prepare detailed item list for response (optimized for mobile)
    $borrowed_items = [];
    foreach ($validated_items as $item) {
        $borrowed_items[] = [
            'kode_barang' => $item['kode_barang'],
            'component_name' => $item['component_name'],
            'color_code' => $item['code_color'],
            'buyer_name' => $item['nama_buyer']
        ];
    }
    
    // Prepare response data (mobile-optimized)
    $response_data = [
        'reservation_number' => $reservationNumber,
        'total_items' => count($validated_items),
        'duration' => $duration_display,
        'location' => $lokasi_tujuan,
        'transaction_id' => $transaction_id,
        'transaction_date' => $transaction_datetime->format('d-m-Y H:i'),
        'return_date' => $return_datetime->format('d-m-Y H:i'),
        'current_server_time' => $current_datetime->format('d-m-Y H:i:s'),
        'borrowed_items' => $borrowed_items,
        'status' => 'Dipinjam'
    ];
    
    // Add mobile-specific optimizations
    if ($isMobile) {
        $response_data['mobile_optimized'] = true;
        $response_data['compact_info'] = [
            'reservation' => $reservationNumber,
            'items_count' => count($validated_items),
            'duration_text' => $duration_display,
            'location_code' => $lokasi_tujuan
        ];
    }
    
    // Send success response
    sendJSONResponse(true, $success_message, $response_data);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log error
    error_log("Error in transaction submission: " . $e->getMessage());
    
    // Log the error to audit_logs
    try {
        $error_details = "Error saat submit peminjaman: " . $e->getMessage();
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $user_type = 'borrower';
        $action_type = 'Error Peminjaman';
        
        $stmt = $conn->prepare("INSERT INTO audit_logs (user_id, user_type, action_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issss", $borrower_id, $user_type, $action_type, $error_details, $ip_address);
        $stmt->execute();
        $stmt->close();
    } catch (Exception $log_error) {
        // If logging fails, just continue - don't break the main error handling
        error_log("Failed to log error to audit_logs: " . $log_error->getMessage());
    }
    
    // Mobile-optimized error message
    $isMobile = isset($_SERVER['HTTP_USER_AGENT']) && 
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false);
    
    if ($isMobile) {
        $error_message = "❌ Gagal memproses: " . $e->getMessage();
    } else {
        $error_message = "Terjadi kesalahan saat memproses permintaan: " . $e->getMessage() . ". Silakan coba lagi.";
    }
    
    // Send error response
    sendJSONResponse(false, $error_message);
}
?>