<?php
// File: topsis_implementation.php
// This file connects the TOPSIS function with the view

// Include the TOPSIS functions
require_once 'topsis_functions.php';

/**
 * Process restocking request
 * This function would be called by an AJAX request from the view
 */
function processRestock($conn, $productId, $amount, $note = '') {
    // Validate input
    $productId = (int)$productId;
    $amount = (int)$amount;
    
    if ($productId <= 0 || $amount <= 0) {
        return [
            'success' => false,
            'message' => 'Invalid product ID or amount'
        ];
    }
    
    // Get current stock
    $query = "SELECT stok FROM barang WHERE id_barang = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "i", $productId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (!$row = mysqli_fetch_assoc($result)) {
        return [
            'success' => false,
            'message' => 'Product not found'
        ];
    }
    
    $currentStock = (int)$row['stok'];
    $newStock = $currentStock + $amount;
    
    // Update stock
    $updateQuery = "UPDATE barang SET stok = ? WHERE id_barang = ?";
    $updateStmt = mysqli_prepare($conn, $updateQuery);
    mysqli_stmt_bind_param($updateStmt, "ii", $newStock, $productId);
    $success = mysqli_stmt_execute($updateStmt);
    
    if (!$success) {
        return [
            'success' => false,
            'message' => 'Failed to update stock: ' . mysqli_error($conn)
        ];
    }
    
    // Log the restock activity
    $logQuery = "INSERT INTO log_restok (id_barang, jumlah, tanggal, catatan) 
                VALUES (?, ?, NOW(), ?)";
    $logStmt = mysqli_prepare($conn, $logQuery);
    mysqli_stmt_bind_param($logStmt, "iis", $productId, $amount, $note);
    mysqli_stmt_execute($logStmt);
    
    return [
        'success' => true,
        'message' => 'Stock updated successfully',
        'new_stock' => $newStock
    ];
}

// If this file is accessed directly through an AJAX request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Database connection
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "ayula_store";
    
    $conn = mysqli_connect($host, $username, $password, $database);
    if (!$conn) {
        echo json_encode([
            'success' => false,
            'message' => 'Database connection failed: ' . mysqli_connect_error()
        ]);
        exit;
    }
    
    // Process based on action
    $action = $_POST['action'];
    
    switch ($action) {
        case 'restock':
            if (isset($_POST['productId']) && isset($_POST['amount'])) {
                $result = processRestock(
                    $conn, 
                    $_POST['productId'], 
                    $_POST['amount'],
                    $_POST['note'] ?? ''
                );
                echo json_encode($result);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Missing required parameters'
                ]);
            }
            break;
            
        // Add other actions as needed
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Unknown action'
            ]);
    }
    
    mysqli_close($conn);
    exit;
}

/**
 * Create table for logging restock activities
 * Run this once to set up the database table
 */
function createRestockLogTable($conn) {
    $query = "CREATE TABLE IF NOT EXISTS log_restok (
        id INT(11) PRIMARY KEY AUTO_INCREMENT,
        id_barang INT(11) NOT NULL,
        jumlah INT(10) NOT NULL,
        tanggal DATETIME NOT NULL,
        catatan TEXT,
        FOREIGN KEY (id_barang) REFERENCES barang(id_barang)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    
    return mysqli_query($conn, $query);
}

/**
 * Export TOPSIS results to CSV
 */
function exportToCSV($data, $filename = 'topsis_results.csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');
    
    // Add header row
    fputcsv($output, ['Rank', 'ID Barang', 'Nama Barang', 'Stok', 'Harga', 'TOPSIS Score']);
    
    // Add data rows
    foreach ($data as $row) {
        fputcsv($output, [
            $row['rank'],
            $row['id_barang'],
            $row['nama_barang'],
            $row['stok'],
            $row['harga'],
            $row['topsis_score']
        ]);
    }
    
    fclose($output);
    exit;
}
?>