<?php
require_once('conn.php');

// Check login status (assuming you have a similar function in PHP)
checkLogin("信息管理");

// Initialize all variables to avoid undefined warnings
$act = isset($_GET['act']) ? $_GET['act'] : '';
$page = isset($_GET['Page']) ? $_GET['Page'] : 1;
$keys = isset($_GET['Keys']) ? urlencode($_GET['Keys']) : '';
$keyscode = isset($_GET['Keys']) ? htmlspecialcharsFix($_GET['Keys']) : '';
$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;

// Handle form submissions and redirects before any output
if ($act == 'add') {
    // Redirect to the add product page
    header("Location: add_product.php?Keys=" . $keys . "&Page=" . $page . ($category_id ? "&category_id=" . $category_id : ""));
    exit();
} else if ($act == 'edit') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    if ($id > 0) {
        // Redirect to the edit product page
        header("Location: edit_product.php?id=" . $id . "&Keys=" . $keys . "&Page=" . $page . ($category_id ? "&category_id=" . $category_id : ""));
        exit();
    }
}

// Handle bulk actions
if ($act == 'postchk') {
    if (isset($_POST['chkbox']) && isset($_POST['chkact'])) {
        $chk_ids = array_map('intval', $_POST['chkbox']);
        $chk_act = (int)$_POST['chkact'];
        
        if (!empty($chk_ids)) {
            $ids_str = implode(',', $chk_ids);
            
            switch ($chk_act) {
                case 0:
                case 1:
                    $sql = "UPDATE customer SET cs_state = " . $chk_act . " WHERE id IN (" . $ids_str . ")";
                    break;
                case -1:
                    $sql = "DELETE FROM products WHERE id IN (" . $ids_str . ")";
                    break;
            }
            
            if (isset($sql)) {
                mysqli_query($conn, $sql);
            }
        }
        
        header("Location: ?Keys=" . $keys . "&Page=" . $page . ($category_id ? "&category_id=" . $category_id : ""));
        exit();
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>产品信息管理</title>
<link rel="stylesheet" href="css/common.css" type="text/css" />
<script language="javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/js.js"></script>
<script type="text/javascript" src="js/SearchArea.js"></script>
<script type="text/javascript" src="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.js"></script>
<style>
    .add_btn {
        background-color: #5cb85c;
        color: white;
        padding: 6px 15px;
        border: none;
        border-radius: 3px;
        cursor: pointer;
        font-weight: bold;
    }
    .add_btn:hover {
        background-color: #449d44;
    }
    .search_panel {
        padding: 15px;
        border-radius: 4px;
        border: 1px solid #ddd;
        margin-bottom: 20px;
    }
    .search_panel label {
        font-weight: bold;
        margin-right: 5px;
    }
    .search_panel .inputTxt {
        width: 200px;
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }
    .search_panel .searchgo {
        padding: 5px 15px;
        background-color: #337ab7;
        color: white;
        border: none;
        border-radius: 3px;
        cursor: pointer;
    }
    .search_panel .searchgo:hover {
        background-color: #286090;
    }
    .select1 {
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 3px;
        min-width: 200px;
    }
</style>
</head>

<body>
<div id="man_zone">
<?php
// Display product list
require_once 'functions.php';

// Get filter category id
$filter_category_id = $category_id;

// Prepare SQL condition for category filtering
$category_condition = '';
if ($filter_category_id > 0) {
    // Get all subcategories of the selected category
    $category_data = buildCategoryTree($conn);
    $all_categories = $category_data['all_categories'];
    
    $category_ids = array($filter_category_id);
    getSubcategoryIds($all_categories, $filter_category_id, $category_ids);
    
    $category_condition = " WHERE category_id IN (" . implode(',', $category_ids) . ")";
}

// Search condition
$search_condition = '';
if (!empty($keyscode)) {
    $search_condition = ($category_condition ? " AND " : " WHERE ") . 
                       "ProductName LIKE '%" . mysqli_real_escape_string($conn, $keyscode) . "%'";
}

// Get total records count using a COUNT query instead of fetching all records
$count_sql = "SELECT COUNT(*) as total FROM products" . $category_condition . $search_condition;
$count_result = mysqli_query($conn, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);
$total_records = $count_row['total'];

// 固定每页显示18条记录(与 customers.php 保持一致)
$pageSize = 18;
$total_pages = ceil($total_records / $pageSize);
if ($total_pages < 1) $total_pages = 1; // 确保至少有一页,即使没有结果

// Validate page number
if (empty($page)) $page = 1;
if ($page == 'end') $page = $total_pages;
if (!is_numeric($page) || $page < 1) $page = 1;
$page = (int)$page;
if ($page > $total_pages) $page = $total_pages;

// Apply pagination
$offset = ($page - 1) * $pageSize;
if ($offset < 0) $offset = 0; // 确保偏移量不为负数

// Fetch only the records for the current page
$sql = "SELECT id, ProductName, ProductImg, category_id FROM products" . 
       $category_condition . $search_condition . " ORDER BY id DESC LIMIT $offset, $pageSize";
$result = mysqli_query($conn, $sql);

$temp_num = $pageSize * ($page - 1);
?>
<div class="search_panel">
    <form method="get" action="">
        <input type="hidden" name="Page" value="1">
        <div style="display: flex; margin-bottom: 10px;style="margin-left: 20px;"">
        <div style="margin-right: 20px;">
            <input type="button" value="+ 新增产品" onClick="location.href='?act=add<?php echo $filter_category_id ? '&category_id='.$filter_category_id : ''; ?>'" class="add_btn" />
        </div>
            <div style="margin-right: 20px;">
                <label>按分类筛选:</label>
                <select name="category_id" class="select1" onchange="this.form.submit()">
                    <option value="0">-- 所有分类 --</option>
                    <?php
                    // Build category tree for filter dropdown
                    $category_data = buildCategoryTree($conn);
                    $cat_tree = $category_data['tree'];
                    
                    // Output options
                    outputCategoryOptions($cat_tree, $filter_category_id);
                    ?>
                </select>
            </div>
            <div>
                <label>关键词搜索:</label>
                <input type="text" name="Keys" value="<?php echo $keyscode; ?>" class="inputTxt" placeholder="请输入产品名称">
                <input type="submit" value="搜索" class="searchgo">
            </div>

        </div>
    </form>
</div>

<form id="form1" method="post" action="?act=postchk&Keys=<?php echo $keys; ?>&Page=<?php echo $page; ?><?php echo $filter_category_id ? '&category_id='.$filter_category_id : ''; ?>">
    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <thead>
            <tr>
                <th width="4%"><input type="checkbox" name="chkall" id="chkall" onClick="chkboxall(this,'chkbox')" /></th>
                <th width="6%">序号</th>
                <th width="25%">产品名称</th>
                <th width="15%">产品分类</th>
                <th width="30%">图片</th>
                <th width="10%">返点规则数量</th>
                <th width="20%">操作</th>
            </tr>
        </thead>
        <tbody>
        <?php
        if (mysqli_num_rows($result) > 0) {
            $temp_num = $pageSize * ($page - 1);
            while ($row = mysqli_fetch_assoc($result)) {
                $temp_num++;
                ?>
                <tr onMouseOver="this.style.background='#F7FCFF'" onMouseOut="this.style.background='#FFFFFF'">
                    <td align="center"><input type="checkbox" name="chkbox[]" value="<?php echo $row['id']; ?>" /></td>
                    <td align="center"><?php echo $temp_num; ?></td>
                    <td align="center"><?php echo htmlspecialcharsFix($row['ProductName']); ?></td>
                    <td align="center">
                        <?php 
                        require_once 'functions.php';
                        echo getCategoryPath($conn, $row['category_id']); 
                        ?>
                    </td>
                    <td align="center"><img src="<?php echo htmlspecialcharsFix($row['ProductImg']); ?>" width="30px"></td>
                    <td align="center">
                        <?php 
                        // Count rebate rules for this product (only where rebate_amount > 0)
                        $rebate_sql = "SELECT COUNT(*) as rebate_count FROM rebate_rules WHERE product_id = " . $row['id'] . " AND rebate_amount > 0";
                        $rebate_result = mysqli_query($conn, $rebate_sql);
                        $rebate_row = mysqli_fetch_assoc($rebate_result);
                        echo $rebate_row['rebate_count']; 
                        ?>
                    </td>
                    <td align="center">
                        <a href="?Keys=<?php echo $keys; ?>&Page=<?php echo $page; ?>&act=edit&id=<?php echo $row['id']; ?><?php echo $filter_category_id ? '&category_id='.$filter_category_id : ''; ?>" class="ico_edit ico">修改</a>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="9" align="center">
                    <?php echo empty($keys) ? 'Sorry,当前暂无信息' : '<a href="?">Sorry,没有找到"' . htmlspecialcharsFix($keyscode) . '"相关的信息,点击返回</a>'; ?>
                </td>
            </tr>
            <?php
        }
        ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="9">
                    <div class="showpagebox">
                    <?php
                    if ($total_pages > 1) {
                        // Build page URL with all parameters
                        $page_params = array();
                        if (!empty($keys)) $page_params[] = "Keys=" . urlencode($keys);
                        if ($filter_category_id > 0) $page_params[] = "category_id=" . $filter_category_id;
                        
                        $page_name = "?" . implode("&", $page_params) . ($page_params ? "&" : "");
                        $page_len = 3;
                        
                        // Previous page links
                        if ($page > 1) {
                            echo "<a href=\"{$page_name}Page=1\">首页</a>";
                            echo "<a href=\"{$page_name}Page=" . ($page-1) . "\">上一页</a>";
                        }
                        
                        // Calculate page range
                        if ($page_len * 2 + 1 >= $total_pages) {
                            $start_page = 1;
                            $end_page = $total_pages;
                        } else {
                            if ($page <= $page_len + 1) {
                                $start_page = 1;
                                $end_page = $page_len * 2 + 1;
                            } else {
                                $start_page = $page - $page_len;
                                $end_page = $page + $page_len;
                            }
                            if ($page + $page_len > $total_pages) {
                                $start_page = $total_pages - $page_len * 2;
                                $end_page = $total_pages;
                            }
                        }
                        
                        // Page numbers
                        for ($i = $start_page; $i <= $end_page; $i++) {
                            if ($i == $page) {
                                echo "<a class=\"current\">$i</a>";
                            } else {
                                echo "<a href=\"{$page_name}Page=$i\">$i</a>";
                            }
                        }
                        
                        // Next page links
                        if ($page < $total_pages) {
                            if ($total_pages - $page > $page_len) {
                                echo "<a href=\"{$page_name}Page=$total_pages\">...$total_pages</a>";
                            }
                            echo "<a href=\"{$page_name}Page=" . ($page+1) . "\">下一页</a>";
                            echo "<a href=\"{$page_name}Page=$total_pages\">尾页</a>";
                        }
                        
                        // Jump to page input
                        echo "<input type=\"text\" id=\"Pagego\" value=\"$page\" 
                              onFocus=\"if(this.value == '$page'){this.value='';}\" 
                              onBlur=\"if(this.value == ''){this.value='$page';}\" 
                              onKeyUp=\"this.value=this.value.replace(/\D/g,'')\" 
                              onKeyDown=\"if(event.keyCode==13){location.href='{$page_name}Page='+document.getElementById('Pagego').value}\" />";
                    }
                    ?>
                    </div>
                    
                    <div class="postchkbox">
                        <select id="chkact" name="chkact">

                            <option value="-1">删除</option>
                        </select>
                        <input type="button" value="执行" onClick="postchk_products(1)" class="btn1" />
                        <input type="button" value="新增" onClick="location.href='?act=add<?php echo $filter_category_id ? '&category_id='.$filter_category_id : ''; ?>'" class="btn1" />
                    </div>
                </td>
            </tr>
        </tfoot>
    </table>
</form>
</div>
<script type="application/javascript">

    function postchk_products(formBtn) {
        // Check if at least one checkbox is selected
        var checkboxes = document.getElementsByName('chkbox[]');
        var isChecked = false;

        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                isChecked = true;
                break;
            }
        }

        if (!isChecked) {
            alert('请至少选择一条数据');
            return false;
        }

        // If at least one checkbox is selected, submit the form
        document.getElementById('form1').submit();
        return true;
    }
</script>
</body>
</html>
<?php mysqli_close($conn); ?>