<?php
require_once 'conn.php';
checklogin("信息管理");
?>
<!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" />
<link rel="stylesheet" href="css/jquery.galpop.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="xheditor-1.1.9/xheditor-1.1.9-zh-cn.min.js"></script>
<script type="text/javascript" src="js/Searchproduct.js"></script>
</head>
<body>
<div id="man_zone">
<?php
$act = $_GET['act'] ?? '';

if ($act == "save") {
    $isedit = false;
    $id = $_POST['id'] ?? '';
    if ($id != "" && is_numeric($id)) {
        $isedit = true;
    }

    $productId = $_POST['productId'] ?? '';
    $num = $_POST['num'] ?? '';
    $price = $_POST['price'] ?? '';

    if ($isedit) {
        $sql = "UPDATE country SET addtime=NOW() WHERE id=$id";
        $conn->query($sql);
        
        $productIds = explode(',', $productId);
        $nums = explode(',', $num);
        $prices = explode(',', $price);
        
        $conn->query("DELETE FROM price WHERE AreaId=$id");
        
        for ($i = 0; $i < count($productIds); $i++) {
            $numVal = empty($nums[$i]) ? 0 : $nums[$i];
            $priceVal = empty($prices[$i]) ? 0 : $prices[$i];
            $sql = "INSERT INTO price (productId, AreaId, num, price) VALUES ($productIds[$i], $id, $numVal, '$priceVal')";
            $conn->query($sql);
        }

        $page = $_GET['Page'] ?? '';
        $keys = urlencode($_GET['Keys'] ?? '');
        $ord = urlencode($_GET['Ord'] ?? '');
        header("Location: ?keys=$keys&Ord=$ord&Page=$page");
        exit;
    } else {
        $sql = "INSERT INTO country (addtime) VALUES (NOW())";
        $conn->query($sql);
        $id = $conn->insert_id;
        
        $productIds = explode(',', $productId);
        $nums = explode(',', $num);
        $prices = explode(',', $price);
        
        for ($i = 0; $i < count($productIds); $i++) {
            $numVal = empty($nums[$i]) ? 0 : $nums[$i];
            $priceVal = empty($prices[$i]) ? 0 : $prices[$i];
            $sql = "INSERT INTO price (productId, AreaId, num, price) VALUES ($productIds[$i], $id, $numVal, '$priceVal')";
            $conn->query($sql);
        }

        header("Location: ?");
        exit;
    }
}

if ($act == "add" || $act == "edit") {
    $id = $_GET['id'] ?? '';
    $isedit = false;
    $countryCode = '';
    $countryName = '';
    $addtime = '';

    if ($id != "" && is_numeric($id)) {
        $isedit = true;
        $sql = "SELECT * FROM country WHERE id = $id";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();
        
        if ($row) {
            $countryCode = $row['countryCode'];
            $countryName = $row['countryName'];
            $addtime = $row['addtime'];
        } else {
            $isedit = false;
        }
    }

    $page = $_GET['Page'] ?? '';
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $hrefstr = "?keys=$keys&Ord=$ord&Page=$page";
?>
    <form name="form1" method="post" action="<?= $hrefstr ?>&act=save">
    <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
        <tbody>
            <tr>
                <th width="8%">国家</th>
                <td><input type="text" id="countryName" name="countryName" readonly value="<?= htmlspecialchars($countryName) ?>" class="txt1" /><input type="hidden" name="id" value="<?= $id ?>" /></td>
            </tr>
            <tr>
                <th width="8%">区号</th>
                <td><input type="text" id="countryCode" name="countryCode" readonly value="<?= htmlspecialchars($countryCode) ?>" class="txt1" /></td>
            </tr>
            <tr>
                <th width="8%">更新日期</th>
                <td><?= $addtime ?></td>
            </tr>           
            <tr>
                <th width="8%">售价管理</th>
                <td>
                <div class="prowapper">             
                    <?php
                    $sql = "SELECT id, ProductName, ProductImg, unit FROM Products WHERE id IN (SELECT productId FROM price WHERE AreaId = $id)";
                    $result = $conn->query($sql);
                    while ($row = $result->fetch_assoc()) {
                    ?>
                        <div class="proitem">
                            <div class="prodelet"></div>
                            <div class="proname"><?= htmlspecialchars($row['ProductName']) ?></div>
                            <div class="propic"><img src="<?= htmlspecialchars($row['ProductImg']) ?>"></div>      
                            <div class="proprice">
                                <?php
                                $sql2 = "SELECT num, price FROM Price WHERE productId = {$row['id']} AND AreaId = $id ORDER BY num ASC";
                                $result2 = $conn->query($sql2);
                                while ($row2 = $result2->fetch_assoc()) {
                                ?>
                                    <div class="priceitem">
                                        <input type="hidden" name="productId" value="<?= $row['id'] ?>">
                                        <label>≥</label>
                                        <input type="number" autocomplete="off" class="txt3 num" name="num" value="<?= $row2['num'] ?>">
                                        <label class='unit'><?= htmlspecialchars($row['unit']) ?></label>
                                        <label>售价</label>
                                        <input type="text" class="txt3 price" autocomplete="off" name="price" value="<?= $row2['price'] ?>">
                                        <label>RMB</label>
                                        <span class="additem"></span>
                                        <span class="delitem"></span>
                                        <span class="note"></span>
                                    </div>
                                <?php
                                }
                                ?>
                            </div>      
                        </div>
                    <?php
                    }
                    ?>
                </div>                  
                </td>
            </tr>
            <tr>
                <th width="8%">产品添加</th>
                <td class="productinput">
                    <input type="text" id="productSearch" class="fastsearch">
                    <div id="productlist" class="productlist"><ul></ul></div>
                </td>
            </tr>          
            <tr>
                <th></th>
                <td>
                    <input type="submit" name="save" id="save" value="确定" class="btn1" />
                    <input type="reset" name="save" id="save" value="重置" class="btn1" />
                    <input type="button" value="返回" class="btn1" onClick="location.href='<?= $hrefstr ?>'" />
                </td>
            </tr>
        </tbody>
    </table>
    </form>
</div>
</body>
</html>
<?php
    exit;
}

if ($act == "postchk") {
    $keys = urlencode($_GET['Keys'] ?? '');
    $ord = urlencode($_GET['Ord'] ?? '');
    $page = $_GET['Page'] ?? '';
    $chkact = $_POST['chkact'] ?? '';
    
    if (isset($_POST['chkbox']) && is_array($_POST['chkbox'])) {
        $ids = implode(',', array_map('intval', $_POST['chkbox']));
        $sql = "DELETE FROM country WHERE id IN ($ids)";
        $conn->query($sql);
    }
    
    header("Location: ?Keys=$keys&Ord=$ord&Page=$page");
    exit;
}

// Main list view
$keys = $_GET['Keys'] ?? '';
$keyscode = $keys;
$ord = $_GET['Ord'] ?? '';
$page = $_GET['Page'] ?? '';

$sql = "SELECT * FROM country WHERE countryName LIKE '%$keyscode%' OR countryCode LIKE '%$keyscode%' ORDER BY id DESC";
$result = $conn->query($sql);
$results = [];
while($row = $result->fetch_assoc()) {
    $results[] = $row;
}

$totalRecords = count($results);
$pageSize = 20;
$totalPages = ceil($totalRecords / $pageSize);

if ($page == "") $page = 1;
if ($page == "end") $page = $totalPages;
if (!is_numeric($page) || $page < 1) $page = 1;
$page = (int)$page;
if ($page > $totalPages) $page = $totalPages;

$start = ($page - 1) * $pageSize;
$currentPageRecords = array_slice($results, $start, $pageSize);

$keys = urlencode($keys);
$ord = urlencode($ord);
$hrefstr = "?keys=$keys";
?>  
    <form id="form1" method="post" action="?act=postchk&Keys=<?= $keys ?>&Ord=<?= $ord ?>&Page=<?= $page ?>" onSubmit="return false">
    <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="30%">国家</th>
                <th width="30%">区号</th>
                <th width="30%">操作</th>
            </tr>
        </thead>
        <tbody>
        <?php
        if (!empty($currentPageRecords)) {
            $tempNum = $start;
            foreach ($currentPageRecords as $row) {
                $tempNum++;
        ?>
            <tr onMouseOver="this.style.background='#F7FCFF'" onMouseOut="this.style.background='#FFFFFF'">
                <td align="center"><input type="checkbox" name="chkbox[]" value="<?= $row['id'] ?>" /></td>
                <td align="center"><?= $tempNum ?></td>
                <td align="center"><?= htmlspecialchars($row['countryName']) ?></td>
                <td align="center"><?= htmlspecialchars($row['countryCode']) ?></td>
                <td align="center">
                    <a href="?Keys=<?= $keys ?>&Ord=<?= $ord ?>&Page=<?= $page ?>&act=edit&id=<?= $row['id'] ?>" class="ico_edit ico">修改</a>
                </td>
            </tr>
        <?php
            }
        } else {
            if ($keys == "") {
        ?>
            <tr>
                <td align="center" colspan="5">Sorry,当前暂无信息</td>
            </tr>
        <?php
            } else {
        ?>
            <tr>
                <td align="center" colspan="5"><a href="?">Sorry,没有找到"<?= htmlspecialchars($keyscode) ?>"相关的信息,点击返回</a></td>
            </tr>
        <?php
            }
        }
        ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5">
                    <div class="showpagebox">
                    <?php
                    if ($totalPages > 1) {
                        $pageName = "?Keys=$keys&Ord=$ord&";
                        $pagelen = 3;

                        if ($page > 1) {
                            echo "<a href=\"{$pageName}Page=1\">首页</a>";
                            echo "<a href=\"{$pageName}Page=" . ($page-1) . "\">上一页</a>";
                        }

                        if ($pagelen * 2 + 1 >= $totalPages) {
                            $startPage = 1;
                            $endPage = $totalPages;
                        } else {
                            if ($page <= $pagelen + 1) {
                                $startPage = 1;
                                $endPage = $pagelen * 2 + 1;
                            } else {
                                $startPage = $page - $pagelen;
                                $endPage = $page + $pagelen;
                            }
                            if ($page + $pagelen > $totalPages) {
                                $startPage = $totalPages - $pagelen * 2;
                                $endPage = $totalPages;
                            }
                        }

                        for ($i = $startPage; $i <= $endPage; $i++) {
                            if ($i == $page) {
                                echo "<a class=\"current\">$i</a>";
                            } else {
                                echo "<a href=\"{$pageName}Page=$i\">$i</a>";
                            }
                        }

                        if ($page < $totalPages) {
                            if ($totalPages - $page > $pagelen) {
                                echo "<a href=\"{$pageName}Page=$totalPages\">...$totalPages</a>";
                            }
                            echo "<a href=\"{$pageName}Page=" . ($page+1) . "\">下一页</a>";
                            echo "<a href=\"{$pageName}Page=$totalPages\">尾页</a>";
                        }

                        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='{$pageName}Page='+document.getElementById('Pagego').value}\" />";
                    }
                    ?>
                    </div>
                    <div class="searchbox">
                        <input type="text" id="keys" value="<?= $keyscode == "" ? "请输入搜索关键词" : htmlspecialchars($keyscode) ?>"
                            onFocus="if(this.value == '<?= $keyscode == "" ? "请输入搜索关键词" : htmlspecialchars($keyscode) ?>'){this.value='';}"
                            onBlur="if(this.value == ''){this.value='<?= $keyscode == "" ? "请输入搜索关键词" : htmlspecialchars($keyscode) ?>';}"
                            onKeyDown="if(event.keyCode==13){location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)}" />
                        <input type="button" id="searchgo" value="go" onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
                    </div>
                    <div class="postchkbox">
                        <select id="chkact" name="chkact">
                            <option value="1">请选择</option>
                            <option value="-1">删除</option>
                        </select>
                        <input type="button" value="执行" onClick="postchk(1)" class="btn1" />
                        <input type="button" value="新增" onClick="location.href='?act=add'" class="btn1" />
                    </div>
                </td>
            </tr>
        </tfoot>
    </table>
    </form>
</div>
<script>
$('.click-open-iframe').galpop({
    contentType: 'iframe',
});
</script>
</body>
</html>