<?php
// Start session
session_start();

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

// Set timezone to Indonesia
date_default_timezone_set('Asia/Jakarta');

// Function to detect mobile device
function isMobileDevice() {
    if (!isset($_SERVER['HTTP_USER_AGENT'])) return false;
    
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $mobileKeywords = [
        'Mobile', 'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
        'Windows Phone', 'Opera Mini', 'IEMobile', 'webOS'
    ];
    
    foreach ($mobileKeywords as $keyword) {
        if (strpos($userAgent, $keyword) !== false) {
            return true;
        }
    }
    
    return false;
}

// Function to send JSON response
function sendJSONResponse($success, $message, $data = null) {
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    
    $isMobile = isMobileDevice();
    
    if ($isMobile && !$success && strlen($message) > 180) {
        $message = substr($message, 0, 177) . '...';
    }
    
    if ($isMobile && $success) {
        $message = "✅ " . $message;
    } elseif ($isMobile && !$success) {
        $message = "❌ " . $message;
    }
    
    $response = [
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'mobile' => $isMobile,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        sendJSONResponse(false, 'Akses tidak diizinkan. Silakan login kembali.');
    } 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 and validate account status
$borrower_id = $_SESSION['user_id'];

try {
    $stmt = $conn->prepare("SELECT id, status, lokasi_posisi FROM borrower_users WHERE id = ?");
    $stmt->bind_param("i", $borrower_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $stmt->close();
        sendJSONResponse(false, 'Data borrower tidak ditemukan');
    }
    
    $borrower_data = $result->fetch_assoc();
    $stmt->close();
    
    if ($borrower_data['status'] !== 'active') {
        sendJSONResponse(false, 'Akun Anda tidak aktif. Silakan hubungi administrator.');
    }
    
} catch (Exception $e) {
    error_log("Error validating borrower: " . $e->getMessage());
    sendJSONResponse(false, 'Terjadi kesalahan saat validasi user');
}

// Validate required fields
$required_fields = [
    'tanggal_transaksi_date' => 'Tanggal transaksi',
    'tanggal_transaksi_time' => 'Waktu transaksi', 
    'tanggal_pengembalian_date' => 'Tanggal pengembalian',
    'tanggal_pengembalian_time' => 'Waktu pengembalian',
    'cart_items' => 'Item peminjaman'
];

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

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

if (json_last_error() !== JSON_ERROR_NONE) {
    sendJSONResponse(false, 'Format data item tidak valid');
}

if (empty($cart_items)) {
    sendJSONResponse(false, 'Pilih minimal satu item untuk dipinjam');
}

// Validate each cart item
foreach ($cart_items as $index => $item) {
    $required_item_fields = [
        'id' => 'ID item',
        'kode_barang' => 'Kode barang',
        'component_name' => 'Nama komponen',
        'status' => 'Status item'
    ];
    
    foreach ($required_item_fields as $field => $label) {
        if (!isset($item[$field]) || empty($item[$field])) {
            sendJSONResponse(false, "Data item ke-" . ($index + 1) . " tidak lengkap: {$label} hilang");
        }
    }
    
    if (!preg_match('/^CP\.\d{4}$/', $item['kode_barang'])) {
        sendJSONResponse(false, "Format kode barang item ke-" . ($index + 1) . " tidak valid");
    }
}

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

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

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

// Validate transaction datetime
try {
    $transaction_datetime = new DateTime($tanggal_transaksi, $timezone);
    $current_datetime = new DateTime('now', $timezone);
    
    // Allow 10 minutes tolerance
    $current_with_tolerance = clone $current_datetime;
    $current_with_tolerance->sub(new DateInterval('PT10M'));
    
    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 server saat ini: {$current_time_display}");
    }
    
    // Check if transaction time is too far in the future (max 24 hours)
    $max_future_time = clone $current_datetime;
    $max_future_time->add(new DateInterval('P1D'));
    
    if ($transaction_datetime > $max_future_time) {
        sendJSONResponse(false, "Waktu transaksi tidak boleh lebih dari 24 jam ke depan");
    }
    
} catch (Exception $e) {
    sendJSONResponse(false, "Format tanggal/waktu transaksi 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());
}

// Validate return date
if ($return_datetime <= $transaction_datetime) {
    sendJSONResponse(false, "Waktu pengembalian harus setelah waktu transaksi");
}

// Check minimum duration (at least 1 hour)
$duration_seconds = $return_datetime->getTimestamp() - $transaction_datetime->getTimestamp();
if ($duration_seconds < 3600) {
    sendJSONResponse(false, "Durasi peminjaman minimal 1 jam");
}

// Check maximum duration (30 days)
$max_allowed_date = clone $transaction_datetime;
$max_allowed_date->add(new DateInterval('P30D'));

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

// Calculate duration for display
$duration_hours = $duration_seconds / 3600;

if ($duration_hours < 24) {
    $duration_display = number_format($duration_hours, 1) . ' jam';
} else {
    $duration_days = $duration_hours / 24;
    if ($duration_days < 7) {
        $duration_display = number_format($duration_days, 1) . ' hari';
    } else {
        $duration_weeks = $duration_days / 7;
        $duration_display = number_format($duration_weeks, 1) . ' minggu';
    }
}

// Generate reservation number
function generateReservationNumber($conn) {
    $timezone = new DateTimeZone('Asia/Jakarta');
    $now = new DateTime('now', $timezone);
    $weekNumber = $now->format('W');
    $year = $now->format('y');
    
    $conn->begin_transaction();
    
    try {
        $lockQuery = "LOCK TABLES stock_transactions READ";
        $conn->query($lockQuery);
        
        $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'];
            $sequence = (int)substr($lastNumber, -3);
            $sequence++;
        } else {
            $sequence = 1;
        }
        
        $reservationNumber = "Resv/{$weekNumber}/{$year}/" . str_pad($sequence, 3, '0', STR_PAD_LEFT);
        
        $conn->query("UNLOCK TABLES");
        $conn->commit();
        
        return $reservationNumber;
        
    } catch (Exception $e) {
        $conn->query("UNLOCK TABLES");
        $conn->rollback();
        throw $e;
    }
}

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

try {
    // Get borrower location
    $lokasi_tujuan = $borrower_data['lokasi_posisi'];
    
    // 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 items and check expiry
    $validated_items = [];
    $unavailable_items = [];
    
    foreach ($cart_items as $item) {
        $item_id = (int)$item['id'];
        
        // Check if item exists and get current status
        $check_stmt = $conn->prepare("
            SELECT csi.id, csi.kode_barang, csi.status, csi.color_id, csi.component_id,
                   csi.tanggal_kedaluwarsa, csi.tanggal_pembuatan, csi.pernah_dipinjam,
                   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();
            $unavailable_items[] = "Item {$item['kode_barang']} tidak ditemukan di database";
            continue;
        }
        
        $current_item = $check_result->fetch_assoc();
        $check_stmt->close();
        
        // Check expiry date
        if (!empty($current_item['tanggal_kedaluwarsa'])) {
            $current_date = new DateTime('now', $timezone);
            $expiry_date = new DateTime($current_item['tanggal_kedaluwarsa'], $timezone);
            
            if ($current_date > $expiry_date) {
                // Update status to Expired
                $update_expired_stmt = $conn->prepare("UPDATE color_stock_items SET status = 'Expired' WHERE id = ?");
                $update_expired_stmt->bind_param("i", $item_id);
                $update_expired_stmt->execute();
                $update_expired_stmt->close();
                
                $unavailable_items[] = "Item {$current_item['kode_barang']} kedaluwarsa pada " . $expiry_date->format('d-m-Y');
                continue;
            }
        }
        
        // Check if item status allows borrowing
        $restricted_statuses = ['Expired', 'Hilang', 'Dipinjam'];
        if (in_array($current_item['status'], $restricted_statuses)) {
            if ($current_item['status'] === 'Dipinjam') {
                $borrower_info_stmt = $conn->prepare("
                    SELECT bu.nama_borrower, bu.lokasi_posisi, st.tanggal_pengembalian
                    FROM transaction_items ti
                    JOIN stock_transactions st ON ti.transaction_id = st.id
                    JOIN borrower_users bu ON st.borrower_id = bu.id
                    WHERE ti.stock_item_id = ? 
                    AND st.status = 'Disetujui'
                    AND st.status_peminjaman = 'Dipinjam'
                    AND ti.dikembalikan = 0
                    ORDER BY st.tanggal_transaksi DESC
                    LIMIT 1
                ");
                $borrower_info_stmt->bind_param("i", $item_id);
                $borrower_info_stmt->execute();
                $borrower_info_result = $borrower_info_stmt->get_result();
                
                if ($borrower_info_result->num_rows > 0) {
                    $borrower_info = $borrower_info_result->fetch_assoc();
                    $return_date = new DateTime($borrower_info['tanggal_pengembalian']);
                    $unavailable_items[] = "Item {$current_item['kode_barang']} sedang dipinjam oleh {$borrower_info['nama_borrower']} hingga " . $return_date->format('d-m-Y H:i');
                } else {
                    $unavailable_items[] = "Item {$current_item['kode_barang']} sedang dipinjam";
                }
                $borrower_info_stmt->close();
            } else {
                $unavailable_items[] = "Item {$current_item['kode_barang']} tidak dapat dipinjam (Status: {$current_item['status']})";
            }
            continue;
        }
        
        $validated_items[] = $current_item;
    }
    
    // Check if any items are unavailable
    if (!empty($unavailable_items)) {
        $error_message = "Beberapa item tidak dapat dipinjam:\n" . implode("\n", $unavailable_items);
        throw new Exception($error_message);
    }
    
    if (empty($validated_items)) {
        throw new Exception("Tidak ada item yang dapat dipinjam");
    }
    
    // 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 transaction
    $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 statuses + expiry dates
    $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
    $update_item_stmt = $conn->prepare("UPDATE color_stock_items SET status = 'Dipinjam' WHERE id = ?");
    
    // **CRITICAL: Prepare statement for expiry date trigger**
    $update_expiry_stmt = $conn->prepare("
        UPDATE color_stock_items 
        SET tanggal_kedaluwarsa = ?, pernah_dipinjam = 1
        WHERE id = ? AND pernah_dipinjam = 0
    ");
    
    $update_quantity_stmt = $conn->prepare("
        UPDATE color_panel_components 
        SET available_quantity = GREATEST(0, available_quantity - 1)
        WHERE color_id = ? AND component_id = ?
    ");
    
    // Calculate 90 days from transaction date
    $expiry_90_days = clone $transaction_datetime;
    $expiry_90_days->add(new DateInterval('P90D'));
    $expiry_90_days_formatted = $expiry_90_days->format('Y-m-d');
    
    foreach ($validated_items as $item) {
        $item_id = $item['id'];
        $color_id = $item['color_id'];
        $component_id = $item['component_id'];
        $pernah_dipinjam = (int)$item['pernah_dipinjam'];
        
        // 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();
        
        // **TRIGGER KEDALUWARSA: Update tanggal_kedaluwarsa jika pertama kali dipinjam**
        if ($pernah_dipinjam == 0) {
            $update_expiry_stmt->bind_param("si", $expiry_90_days_formatted, $item_id);
            $update_expiry_stmt->execute();
            
            // Log the expiry update
            error_log("Item {$item['kode_barang']} pertama kali dipinjam. Tanggal kedaluwarsa diubah menjadi 90 hari: {$expiry_90_days_formatted}");
        }
        
        // Decrease available quantity
        $update_quantity_stmt->bind_param("ii", $color_id, $component_id);
        $update_quantity_stmt->execute();
    }
    
    $stmt->close();
    $update_item_stmt->close();
    $update_expiry_stmt->close();
    $update_quantity_stmt->close();
    
    // Activity logging
    $activity_details = "berhasil meminjam " . count($validated_items) . " item dengan reservasi {$reservationNumber}. Durasi: {$duration_display}. Lokasi tujuan: {$lokasi_tujuan}";
    log_activity($conn, $borrower_id, 'borrower', 'Peminjaman Diproses', $activity_details);
    
    // Audit logging
    $log_details = "borrower ID: $borrower_id berhasil memproses peminjaman dengan ID: $transaction_id untuk " . count($validated_items) . " item (Durasi: $duration_display) ke lokasi {$lokasi_tujuan} - Status langsung Dipinjam";
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 255);
    $user_type = 'borrower';
    $action_type = 'Submit Peminjaman';
    
    $audit_stmt = $conn->prepare("INSERT INTO audit_logs (user_id, user_type, action_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
    $audit_details = $log_details . " [User-Agent: {$user_agent}]";
    $audit_stmt->bind_param("issss", $borrower_id, $user_type, $action_type, $audit_details, $ip_address);
    $audit_stmt->execute();
    $audit_stmt->close();
    
    // Commit transaction
    $conn->commit();
    
    // Detect mobile
    $isMobile = isMobileDevice();
    
    // Prepare success message
    if ($isMobile) {
        $success_message = "Peminjaman berhasil!<br>" . 
                          "<strong>No:</strong> {$reservationNumber}<br>" . 
                          "<strong>Item:</strong> " . count($validated_items) . " item<br>" . 
                          "<strong>Durasi:</strong> {$duration_display}<br>" . 
                          "<strong>Ke:</strong> {$lokasi_tujuan}<br>" . 
                          "<small>Status: Dipinjam (langsung disetujui)</small>";
    } 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 item list
    $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'],
            'id' => $item['id']
        ];
    }
    
    // Response data
    $response_data = [
        'reservation_number' => $reservationNumber,
        'total_items' => count($validated_items),
        'duration' => $duration_display,
        'duration_hours' => round($duration_hours, 1),
        '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',
        'keterangan' => $keterangan ?: null,
        'expiry_trigger_info' => 'Item yang baru pertama kali dipinjam akan memiliki masa kedaluwarsa 90 hari dari tanggal peminjaman.'
    ];
    
    // Mobile 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,
            'success_emoji' => '✅'
        ];
    }
    
    sendJSONResponse(true, $success_message, $response_data);
    
} catch (Exception $e) {
    // Rollback on error
    $conn->rollback();
    
    $error_message = $e->getMessage();
    error_log("Error in transaction submission (Borrower ID: {$borrower_id}): " . $error_message);
    
    // Log error to audit
    try {
        $error_details = "Error saat submit peminjaman: " . $error_message . " | Items count: " . count($cart_items);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 255);
        $user_type = 'borrower';
        $action_type = 'Error Peminjaman';
        
        $error_stmt = $conn->prepare("INSERT INTO audit_logs (user_id, user_type, action_type, details, ip_address) VALUES (?, ?, ?, ?, ?)");
        $full_error_details = $error_details . " [User-Agent: {$user_agent}]";
        $error_stmt->bind_param("issss", $borrower_id, $user_type, $action_type, $full_error_details, $ip_address);
        $error_stmt->execute();
        $error_stmt->close();
    } catch (Exception $log_error) {
        error_log("Failed to log error to audit_logs: " . $log_error->getMessage());
    }
    
    $isMobile = isMobileDevice();
    
    if ($isMobile) {
        if (strlen($error_message) > 100) {
            $error_message = "Gagal memproses: " . substr($error_message, 0, 97) . "...";
        } else {
            $error_message = "Gagal memproses: " . $error_message;
        }
    } else {
        $error_message = "Terjadi kesalahan saat memproses permintaan: " . $error_message . ". Silakan coba lagi atau hubungi administrator jika masalah berlanjut.";
    }
    
    sendJSONResponse(false, $error_message);
}
?>