<?php
// delete_color_data.php
// Start session
session_start();

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

// Set content type to JSON for all responses
header('Content-Type: application/json');

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'ID warna tidak valid']);
    exit();
}

$color_id = $_GET['id'];

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Check if the color exists
    $check_query = "SELECT c.*, b.nama_buyer 
                   FROM master_color_panel_surabaya c
                   JOIN buyers_surabaya b ON c.buyer_id = b.id
                   WHERE c.id = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("i", $color_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        throw new Exception("Data warna tidak ditemukan");
    }
    
    $color_data = $check_result->fetch_assoc();
    
    // Check if there are any borrowed items for this color
    $check_borrowed_query = "SELECT COUNT(*) as count
                           FROM color_stock_items_surabaya csi 
                           JOIN transaction_items_surabaya ti ON csi.id = ti.stock_item_id
                           JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id
                           WHERE csi.color_id = ? AND (st.status_peminjaman = 'Dipinjam' OR st.status = 'OnProccesing')";
    $check_borrowed_stmt = $conn->prepare($check_borrowed_query);
    $check_borrowed_stmt->bind_param("i", $color_id);
    $check_borrowed_stmt->execute();
    $borrowed_result = $check_borrowed_stmt->get_result();
    $borrowed_count = $borrowed_result->fetch_assoc()['count'];
    
    if ($borrowed_count > 0) {
        throw new Exception("Tidak dapat menghapus data warna karena masih ada item yang sedang dipinjam atau dalam proses peminjaman");
    }
    
    // Delete all stock items for this color (this will cascade to delete from transaction_items_surabaya)
    $delete_stock_stmt = $conn->prepare("DELETE FROM color_stock_items_surabaya WHERE color_id = ?");
    $delete_stock_stmt->bind_param("i", $color_id);
    $delete_stock_stmt->execute();
    
    // Delete all panel components for this color
    $delete_components_stmt = $conn->prepare("DELETE FROM color_panel_components_surabaya WHERE color_id = ?");
    $delete_components_stmt->bind_param("i", $color_id);
    $delete_components_stmt->execute();
    
    // Delete the color panel record
    $delete_color_stmt = $conn->prepare("DELETE FROM master_color_panel_surabaya WHERE id = ?");
    $delete_color_stmt->bind_param("i", $color_id);
    $delete_color_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Log activity
    log_activity(
        $conn, 
        $it_id, 
        'it', 
        'Delete Color', 
        "IT user deleted color: {$color_data['code_color']} (Buyer: {$color_data['nama_buyer']})"
    );
    
    // Return success response
    echo json_encode([
        'success' => true, 
        'message' => "Data warna {$color_data['code_color']} berhasil dihapus"
    ]);
    
} catch (Exception $e) {
    // Rollback transaction
    $conn->rollback();
    
    // Return error response
    echo json_encode([
        'success' => false, 
        'message' => "Gagal menghapus data warna: " . $e->getMessage()
    ]);
}

exit();
?>