<?php
// report_handler.php - Updated to handle multiple products
// Place this file in the same directory as your productlist.php

// Koneksi ke database
$servername = "localhost";
$username = "root"; // Sesuaikan dengan username database kamu
$password = ""; // Sesuaikan dengan password database kamu
$database = "ayula_store"; // Sesuaikan dengan nama database kamu

$conn = new mysqli($servername, $username, $password, $database);

// Function for logging
function log_debug($message) {
    file_put_contents('report_debug.log', date('[Y-m-d H:i:s] ') . $message . "\n", FILE_APPEND);
}

log_debug('Report script started');
log_debug('POST data: ' . json_encode($_POST));
log_debug('FILES data: ' . json_encode($_FILES));

// Periksa koneksi
if ($conn->connect_error) {
    log_debug("Connection failed: " . $conn->connect_error);
    die(json_encode(['success' => false, 'message' => 'Koneksi database gagal: ' . $conn->connect_error]));
}

// Cek action yang diminta
if (isset($_POST['action']) && $_POST['action'] == 'create_report') {
    createReport($conn);
} else {
    log_debug("Invalid action");
    echo json_encode(['success' => false, 'message' => 'Aksi tidak valid']);
}

function createReport($conn) {
    // Ambil data dari form
    $id_barang_array = isset($_POST['id_barang']) ? (is_array($_POST['id_barang']) ? $_POST['id_barang'] : [$_POST['id_barang']]) : [];
    $jumlah_array = isset($_POST['jumlah']) ? (is_array($_POST['jumlah']) ? $_POST['jumlah'] : [$_POST['jumlah']]) : [];
    $harga_array = isset($_POST['harga']) ? (is_array($_POST['harga']) ? $_POST['harga'] : [$_POST['harga']]) : [];
    
    log_debug("Processing products: " . json_encode($id_barang_array));
    
    // Validasi data
    if (empty($id_barang_array) || empty($jumlah_array) || empty($harga_array)) {
        log_debug("Missing required data");
        echo json_encode(['success' => false, 'message' => 'Semua field harus diisi']);
        return;
    }
    
    if (count($id_barang_array) != count($jumlah_array) || count($id_barang_array) != count($harga_array)) {
        log_debug("Data count mismatch");
        echo json_encode(['success' => false, 'message' => 'Jumlah data tidak sesuai']);
        return;
    }
    
    // Handle upload gambar nota
    $upload_dir = '../uploads/nota/';
    
    // Buat direktori jika belum ada
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $image_name = '';
    
    if (isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] == 0) {
        // Generate nama file unik
        $file_extension = pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION);
        $image_name = 'nota_' . time() . '_' . mt_rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $image_name;
        
        // Validasi tipe file
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array(strtolower($file_extension), $allowed_types)) {
            log_debug("Invalid file type: " . $file_extension);
            echo json_encode(['success' => false, 'message' => 'Format file tidak didukung. Gunakan JPG, JPEG, PNG, atau GIF']);
            return;
        }
        
        // Validasi ukuran file (max 5MB)
        if ($_FILES['receipt_image']['size'] > 5 * 1024 * 1024) {
            log_debug("File too large: " . $_FILES['receipt_image']['size']);
            echo json_encode(['success' => false, 'message' => 'Ukuran file terlalu besar (maksimum 5MB)']);
            return;
        }
        
        // Upload file
        if (!move_uploaded_file($_FILES['receipt_image']['tmp_name'], $target_file)) {
            log_debug("Failed to upload file");
            echo json_encode(['success' => false, 'message' => 'Gagal mengunggah gambar']);
            return;
        }
        
        log_debug("File uploaded successfully: " . $image_name);
    } else {
        log_debug("No image file uploaded");
        echo json_encode(['success' => false, 'message' => 'Gambar nota harus diunggah']);
        return;
    }
    
    // Mulai transaksi
    $conn->begin_transaction();
    
    try {
        // Buat ID report otomatis (format: RPT-YYYYMMDDxxx)
        $date = date('Ymd');
        $query = "SELECT MAX(SUBSTRING(id_report, 12)) as last_id FROM report WHERE id_report LIKE 'RPT-$date%'";
        $result = $conn->query($query);
        $row = $result->fetch_assoc();
        $last_id = $row['last_id'] ?? 0;
        $report_id = 'RPT-' . $date . str_pad(intval($last_id) + 1, 3, '0', STR_PAD_LEFT);
        
        log_debug("Generated report ID: " . $report_id);
        
        // Loop through each product and insert into report table
        for ($i = 0; $i < count($id_barang_array); $i++) {
            $id_barang = $id_barang_array[$i];
            $jumlah = $jumlah_array[$i];
            $harga = $harga_array[$i];
            
            log_debug("Inserting product: ID=$id_barang, Qty=$jumlah, Price=$harga");
            
            // Simpan data ke tabel report
            $query = "INSERT INTO report (id_report, id_barang, tanggal, jumlah, harga, image) 
                     VALUES (?, ?, NOW(), ?, ?, ?)";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('sssss', $report_id, $id_barang, $jumlah, $harga, $image_name);
            $stmt->execute();
            
            if ($stmt->affected_rows <= 0) {
                throw new Exception("Gagal menyimpan data report untuk produk ID: $id_barang");
            }
            
            $stmt->close();
        }
        
        // Commit transaksi
        $conn->commit();
        
        log_debug("Transaction committed successfully");
        
        echo json_encode([
            'success' => true, 
            'message' => 'Data berhasil ditambahkan ke laporan', 
            'report_id' => $report_id,
            'product_count' => count($id_barang_array),
            'image_url' => '/ayula-store/uploads/nota/' . $image_name
        ]);
        
    } catch (Exception $e) {
        // Rollback transaksi jika terjadi kesalahan
        $conn->rollback();
        
        log_debug("Error: " . $e->getMessage());
        
        // Hapus file gambar jika upload sudah terjadi
        if (!empty($image_name) && file_exists($upload_dir . $image_name)) {
            unlink($upload_dir . $image_name);
            log_debug("Deleted uploaded file due to error");
        }
        
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
}
?>