<?php
// Set flag that this is a parent file
define( '_FEXEC', 1 );
require('includes/application_top.php');

session_start(); // Ensure session is started
if (isset($_SESSION['import_success'])) {
    echo '<div class="alert alert-success" role="alert">' . $_SESSION['import_success'] . '</div>';
    unset($_SESSION['import_success']); // Clear the message after displaying
}

// Set action variable (retrieve from GET or POST)
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

// Debugging step: print the action value to understand if it's being set correctly
 //echo "<pre>Action: $action</pre>"; // Uncomment this line to debug the action value
$id = $FREQUEST->getvalue('id', 'int', '0');


// Clear seat_plan table if the clear button was pressed
if (isset($_POST['clear_table'])) {
    tep_db_query("TRUNCATE TABLE seat_plan");
    $_SESSION['message'] = "Seat plan table has been cleared!";
    header("Location: seatplan_generator.php"); // Adjust the redirection if needed
    exit;
}

if ($action == "delete") {


    // Fetch all subcategories recursively for the given category
    function fetchSubcategories($parent_id) {
        $subcategories = [];
        $query = tep_db_query("SELECT categories_id FROM " . TABLE_CATEGORIES . " WHERE parent_id = '" . (int)$parent_id . "'");
        while ($row = tep_db_fetch_array($query)) {
            $subcategories[] = $row['categories_id'];
            $subcategories = array_merge($subcategories, fetchSubcategories($row['categories_id'])); // Recursive call
        }
        return $subcategories;
    }

    // Fetch all related categories and subcategories
    $all_category_ids = fetchSubcategories($id);
    $all_category_ids[] = $id; // Include the parent category itself

    // Convert category IDs to a comma-separated string
    $all_category_ids_str = implode(',', $all_category_ids);

    // Delete associated products for all categories
    $id_query = tep_db_query("SELECT products_id FROM " . TABLE_PRODUCTS . " WHERE parent_id IN (" . $all_category_ids_str . ")");
    $pid_ids = [];
    while ($id_result = tep_db_fetch_array($id_query)) {
        $pid_ids[] = "'" . $id_result['products_id'] . "'";
    }

    if (!empty($pid_ids)) {
        $pid_ids_str = implode(',', $pid_ids);
        tep_db_query("DELETE FROM " . TABLE_PRODUCTS_TO_CATEGORIES . " WHERE products_id IN (" . $pid_ids_str . ")");
        tep_db_query("DELETE FROM " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products_id IN (" . $pid_ids_str . ")");
        tep_db_query("DELETE FROM " . TABLE_PRODUCTS . " WHERE parent_id IN (" . $all_category_ids_str . ")");
    }

    // Delete categories and descriptions
    tep_db_query("DELETE FROM " . TABLE_CATEGORIES . " WHERE categories_id IN (" . $all_category_ids_str . ")");
    tep_db_query("DELETE FROM " . TABLE_CATEGORIES_DESCRIPTION . " WHERE categories_id IN (" . $all_category_ids_str . ")");
 
    // Redirect after deletion
    header("Location: seatplan_generator.php");
    exit;
}

// Only generate a new seat plan if the action is set to "add_more"
if ($action == 'add_more') {    
    // Fetch the next available categories_id
    $categories_query = tep_db_query("SELECT MAX(categories_id) AS max_id FROM " . TABLE_CATEGORIES);
    $categories = tep_db_fetch_array($categories_query);
    $next_cat_id = ($categories['max_id'] !== null) ? $categories['max_id'] + 1 : 1; // If NULL, start from 1

    // Fetch the current number of shows and set $show_number for the new show
    $show_number_query = tep_db_query("SELECT COUNT(*) AS show_count FROM " . TABLE_CATEGORIES . " WHERE parent_id = 0");
    $show_count = tep_db_fetch_array($show_number_query);
    $show_number = ($show_count['show_count'] !== null) ? $show_count['show_count'] + 1 : 1; // Increment for the next SHOW

    $sort_order = $next_cat_id; // Initialize sort order

    // Fetch the next available products_id to avoid duplicates
    $next_product_id_result = tep_db_query("SELECT MAX(products_id) AS max_product_id FROM " . TABLE_PRODUCTS);
    $next_product_id_row = tep_db_fetch_array($next_product_id_result);
    $next_product_id = ($next_product_id_row['max_product_id'] !== null) ? $next_product_id_row['max_product_id'] + 1 : 1; // Start at 1 if empty

    // Step 1: Insert the main category (e.g., the event)
    $sql = "INSERT INTO " . TABLE_CATEGORIES . " (categories_id, parent_id, sort_order, categories_status, plan_id, manufacturers_id, section_id) 
            VALUES ($next_cat_id, 0, $sort_order, 1, 3, 5, $next_cat_id)";
    tep_db_query($sql);

    // Step 2: Insert into categories_description for the main category
    $sql = "INSERT INTO " . TABLE_CATEGORIES_DESCRIPTION . " (categories_id, language_id, categories_name, categories_heading_title, section_id) 
            VALUES ($next_cat_id, 1, 'SHOW $show_number', 'SHOW $show_number', $next_cat_id)";
    tep_db_query($sql);

    // Step 3: Insert products and assign them to the root category
    $get_products_result = tep_db_query("SELECT * FROM seat_plan ORDER BY products_id ASC");

    while ($product = tep_db_fetch_array($get_products_result)) {
        $current_product_id = $product['products_id'] + $next_product_id;

        // Insert products into the products table, adjusting products_id to avoid duplicates
        $sql = "INSERT INTO " . TABLE_PRODUCTS . " (
            products_id, products_quantity, products_status, color_code, section_id, parent_id, products_x, products_y, products_w, products_h, products_r, products_sx, products_sy, product_type
        ) VALUES (
            $current_product_id,
            '" . tep_db_input($product['products_quantity']) . "',
            " . (int)$product['products_status'] . ",
            '" . tep_db_input($product['color_code']) . "',
            $next_cat_id,
            $next_cat_id,
            " . (int)$product['products_x'] . ",
            " . (int)$product['products_y'] . ",
            " . (int)$product['products_w'] . ",
            " . (int)$product['products_h'] . ",
            " . (int)$product['products_r'] . ",
			" . (int)$product['products_sx'] . ",
			" . (int)$product['products_sy'] . ",
			'" . tep_db_input($product['product_type']) . "'  /* Now properly quoted */
        )";
        tep_db_query($sql);

        // Insert into products_description
        $sql = "INSERT INTO " . TABLE_PRODUCTS_DESCRIPTION . " (products_id, products_name, products_number, products_description, section_id) 
                VALUES ($current_product_id, '" . tep_db_input($product['products_name']) . "', '" . tep_db_input($product['products_number']) . "', '" . tep_db_input($product['products_name']) . "', $next_cat_id)";
        tep_db_query($sql);

        // Insert into products_to_categories
        $sql = "INSERT INTO " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id, section_id) 
                VALUES ($current_product_id, $next_cat_id, $next_cat_id)";
        tep_db_query($sql);
    }

    // Step 4: Set product_type and products_sku based on status
    $sql = "UPDATE " . TABLE_PRODUCTS . " 
            SET products_sku = CASE WHEN products_status = 1 THEN 1 ELSE 0 END 
            WHERE section_id = $next_cat_id";
    tep_db_query($sql);
	
	


    // Redirect after generation to prevent re-execution on page refresh
    header("Location: seatplan_generator.php");
    exit;
}
	$seatPlanData = loadSeatPlan();
$disableGenerate = empty($seatPlanData); // true if table is empty

// Function to load the seat plan data using tep_db_query
function loadSeatPlan() {
    $query = "SELECT * FROM seat_plan ORDER BY products_id";
    $result = tep_db_query($query);

    $seatPlanData = [];
    while ($cell = tep_db_fetch_array($result)) {
        $seatPlanData[] = $cell;
    }
    return $seatPlanData;
}

// Function to display contents of seat_plan table in a simple table format using tep_db_query
function displaySeatPlan() {
    $query = "SELECT * FROM seat_plan ORDER BY products_id";
    $result = tep_db_query($query);

    echo '<h2>Seat Plan Table Data</h2>';
    echo '<table border="1" cellpadding="10" cellspacing="0" style="width: 100%; border-collapse: collapse;">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>ID</th><th>Products Quantity</th><th>Products Name</th><th>Products Number</th><th>Color Code</th><th>Products Status</th><th>Products X</th><th>Products Y</th><th>Products W</th><th>Products H</th><th>Products R</th><th>Products SX</th><th>Products SY</th><th>Products Type</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    
    while ($row = tep_db_fetch_array($result)) {
        echo '<tr>';
        echo '<td>' . htmlspecialchars($row['products_id']) . '</td>';
        echo '<td>' . htmlspecialchars($row['products_quantity']) . '</td>';
        echo '<td>' . htmlspecialchars($row['products_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['products_number']) . '</td>';
        echo '<td>' . htmlspecialchars($row['color_code']) . '</td>';
        echo '<td>' . htmlspecialchars($row['products_status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['products_x']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_y']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_w']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_h']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_r']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_sx']) . '</td>';
		echo '<td>' . htmlspecialchars($row['products_sy']) . '</td>';
		echo '<td>' . htmlspecialchars($row['product_type']) . '</td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';
}

// Load the seat plan data
$seatPlanData = loadSeatPlan();
?>

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script src="includes/javascript/jquery-ui.css"></script>
<script src="includes/javascript/jquery-3.6.0.min.js"></script>
<script src="includes/javascript/jquery-ui-1.8.13.custom.min.js"></script>
<style>
#content {
	padding:20px;
	margin-top:10px;
}
#content label{
	font-size: 14px;
}
#seat-plan-list {
	padding:10px;
}
.table_info td {
	background: #eee;
}
</style>

</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">  
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<table border="0" width="100%" cellpadding="3" cellspacing="6">
<tr class="dataTableHeadingRow">
	<td width="100%" class="main">
	<b><?php echo HEADING_TITLE_1; ?> [v2]</b>
	<p><?php echo HEADING_TITLE_2; ?></p>
	<p><?php echo HEADING_TITLE_3; ?></p>
	</td>
</tr></table>
<!-- body //-->
<!-- Frontend UI -->
<div id="content">
<table border="0" class="table_info" cellpadding="10" cellspacing="5">
  <tbody>

    <tr>
      <td><label for="csv_file"><?php echo TEXT_IMPORT; ?>:</label></td>
      <td>
        <form method="POST" action="import.php" enctype="multipart/form-data" class="d-flex align-items-center">
    <div class="me-2 flex-grow-1">
        <input class="btn btn-primary btn-sm w-100" type="file" name="csv_file" accept=".csv" required>
    </div>
    <div>
        <button class="btn btn-primary btn-sm" type="submit" name="import_csv"><?php echo TEXT_IMPORT_CSV; ?></button>
    </div>
</form>
      </td>
    </tr>

    <tr>
      <td><label for="print_data"><?php echo TEXT_CHECK_DATA; ?>:</label></td>
      <td>
        <form method="GET" action="print_seatplan.php">
          <button class="btn btn-primary btn-sm" name="print_data" type="submit"><?php echo TEXT_PRINT_DATA; ?></button>
        </form>
      </td>
    </tr>

    <tr>
      <td>
	  <label for="generate"><?php echo TEXT_GENERATE_SEATPLAN; ?>:</label></td>
      <td>
        <form action="seatplan_generator.php" method="GET">
          <input type="hidden" name="action" value="add_more">
          <button class="btn btn-primary btn-sm" name="generate" type="submit"
            <?php echo $disableGenerate ? 'disabled title="'.TEXT_NO_DATA_AVAILABLE.'"' : ''; ?>>
            <?php echo TEXT_GENERATE; ?>
          </button>
          <?php if ($disableGenerate): ?>
            <small style="color:red;"><?php echo TEXT_NO_DATA; ?></small>
          <?php endif; ?>
        </form>
      </td>

    </tr>

    <tr>
      <td><label for="clear_table"><?php echo TEXT_CLEAR_TABLE; ?>:</label></td>
      <td>
    <form method="POST" action="seatplan_generator.php">
      <button class="btn btn-danger btn-sm" type="submit" name="clear_table"><?php echo TEXT_CLEAR_TABLE; ?></button>
    </form>
  </td>
</tr>
  </tbody>
</table>
<!-- Export Button 
    <form method="GET" action="export.php">
        <button class="btn btn-primary btn-sm" type="submit" name="export" value="csv">Export And Save CSV</button>
    </form>-->
<table>
<tr>
<td width="40%" class="main">
	<b><?php echo HEADING_TITLE_5; ?></b>
	  </td>
</tr>
</table>

<div id="seat-plan-list">
    <!-- Seat plan list will be loaded here -->	
</div>

<script>
    
	// Add a click event to the hard refresh button
	$('#hard-refresh-btn').on('click', function() {
		// Perform a hard refresh (full reload) of the page
		location.reload(true);
	});

	function loadSeatPlanList() {
        $.ajax({
            url: 'ajax_seatplan_list.php',
            type: 'GET',
            success: function (data) {
                $('#seat-plan-list').html(data);
            },
            error: function () {
                alert('<?php echo TEXT_FAILED_IMPORT; ?>');
            }
        });
    }

    // Load the seat plan list when the page loads
    $(document).ready(function () {
        loadSeatPlanList();
    });
	
    function confirmDeletion(categoryId) {
        // Display a confirmation dialog
        if (confirm("<?php echo TEXT_WARNING_DELETE; ?>")) {
            // If confirmed, redirect to the delete URL
            window.location.href = "seatplan_generator.php?action=delete&id=" + categoryId + "#footer";
            return true;
        } else {
            // If not confirmed, do nothing
            return false;
        }
    }
</script>


<table border="0" width="100%" cellpadding="3" cellspacing="6">
<tr class="dataTableHeadingRow">
	<td width="100%" class="main">
	<b><?php echo TEXT_GOTO_DETAILS; ?></b>

	</td>
</tr></table>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>