<?php
session_start();
require_once "db_connection.php";

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$query = "SELECT * FROM karshenasan WHERE request_type LIKE '%تاسیس%' OR request_type LIKE '%موافقت%'";

$result = $conn->query($query);

function dateDiffInDays($date1, $date2) {
    $diff = strtotime($date1) - strtotime($date2);
    return ceil($diff / (60 * 60 * 24));
}

function jalaliToGregorian($jy, $jm, $jd) {
    $jy += 1595;
    $days = -355668 + (365 * $jy) + (intdiv($jy, 33) * 8) + intdiv(($jy % 33) + 3, 4) + $jd + (($jm < 7) ? ($jm - 1) * 31 : (($jm - 7) * 30) + 186);
    $gy = 400 * intdiv($days, 146097);
    $days %= 146097;
    if ($days > 36524) {
        $gy += 100 * intdiv(--$days, 36524);
        $days %= 36524;
        if ($days >= 365) $days++;
    }
    $gy += 4 * intdiv($days, 1461);
    $days %= 1461;
    if ($days > 365) {
        $gy += intdiv($days - 1, 365);
        $days = ($days - 1) % 365;
    }
    $gd = $days + 1;
    $sal_a = array(0, 31, (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    for ($gm = 0; $gm < 13; $gm++) {
        if ($gd <= $sal_a[$gm]) break;
        $gd -= $sal_a[$gm];
    }
    return sprintf('%04d-%02d-%02d', $gy, $gm, $gd);
}

function convertJalaliToGregorian($jalaliDate) {
    list($jy, $jm, $jd) = explode('-', $jalaliDate);
    return jalaliToGregorian((int)$jy, (int)$jm, (int)$jd);
}

$currentDate = date('Y-m-d');
?>

<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <title>جدول پرونده‌ها</title>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.rtl.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        body { background-color: #f8f9fa; direction: rtl; }
        .expired { background-color: red !important; color: white !important; }
        .resolved { background-color: blue !important; color: white !important; }
        .uploaded { background-color: green !important; color: white !important; }
        thead th {
          position: sticky;
          top: 0;
          background-color: #343a40;
          color: white;
          z-index: 10;
    }
    .expert-box {
    border: 1px solid #ccc;
    background-color: #f0f0f0;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.9rem;
    margin-top: 6px;
    display: inline-block;
    color: #333;
}

    </style>
</head>
<body>
<div class="container mt-4">
    <h4 class="text-center mb-4">نمایش پرونده های نظارت اراضی شش ماهه</h4>
    <div class="row mb-3">
        <div class="row mb-3">
        <div class="col-md-2">
            <a href="reporter_nezarat.php" class="btn btn-success w-100">
                <i class="fas fa-file-excel"></i> گزارش اکسل
            </a>
        </div>
        <div class="col-md-3"><input type="text" id="searchInput" class="form-control" placeholder="جستجو..."></div>
        <div class="col-md-3">
            <select id="requestFilter" class="form-select">
                <option value="">نوع درخواست</option>
                <?php
                $requestTypes = $conn->query("SELECT DISTINCT request_type FROM karshenasan");
                while ($r = $requestTypes->fetch_assoc()) {
                    echo "<option value='{$r['request_type']}'>{$r['request_type']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-2">
            <select id="stepFilter" class="form-select">
                <option value="">همه مراحل</option>
                <?php for ($i = 1; $i <= 10; $i++) echo "<option value='$i'>مرحله $i</option>"; ?>
            </select>

        </div>
        <div class="col-md-2">
            <select id="colorFilter" class="form-select">
                <option value="">وضعیت مرحله</option>
                <option value="expired">منقضی (قرمز)</option>
                <option value="resolved">بررسی‌شده (آبی)</option>
                <option value="uploaded">دارای گزارش (سبز)</option>
            </select>
        </div>
        <div class="col-md-2">
            <input type="text" id="expertNameFilter" class="form-control" placeholder="نام کارشناس مرحله">
        </div>
    </div>

    <?php if ($result->num_rows > 0) { ?>
        <table class="table table-bordered table-hover">
            <thead class="table-dark">
  <tr>
    <th>شماره</th>

    <th>
      نام
      <select class="form-select mt-1 column-filter" data-column="1">
        <option value="">همه</option>
      </select>
    </th>

    <th>
      نام خانوادگی
      <select class="form-select mt-1 column-filter" data-column="2">
        <option value="">همه</option>
      </select>
    </th>

    <th>
      شماره تماس
      <select class="form-select mt-1 column-filter" data-column="3">
        <option value="">همه</option>
      </select>
    </th>

    <th>
      کد ملی
      <select class="form-select mt-1 column-filter" data-column="4">
        <option value="">همه</option>
      </select>
    </th>

    <th>
      نوع درخواست
      <select class="form-select mt-1 column-filter" data-column="5">
        <option value="">همه</option>
        <?php
        $types = $conn->query("SELECT DISTINCT request_type FROM karshenasan");
        while ($t = $types->fetch_assoc()) {
            echo "<option value='" . htmlspecialchars($t['request_type']) . "'>"
                 . htmlspecialchars($t['request_type']) .
                 "</option>";
        }
        ?>
      </select>
    </th>

    <th>
      تاریخ ثبت
      <select class="form-select mt-1 column-filter" data-column="6">
        <option value="">همه</option>
      </select>
    </th>

    <?php for ($i = 1; $i <= 10; $i++): ?>
      <th>
        مرحله <?= $i ?>
        <select class="form-select mt-1 stage-color-filter" data-step="<?= $i ?>">
          <option value="">همه</option>
          <option value="expired">قرمز</option>
          <option value="resolved">آبی</option>
          <option value="uploaded">سبز</option>
        </select>
      </th>
    <?php endfor; ?>

    <th>توضیحات</th>
  </tr>
</thead>



            <tbody>
            <?php $rowNumber = 1;
            while ($row = $result->fetch_assoc()) { ?>
                <tr data-id="<?= $row['id'] ?>">
                    <td class="row-index"><?= $rowNumber++ ?></td>
                    <td><?= $row['first_name'] ?></td>
                    <td><?= $row['last_name'] ?></td>
                    <td><?= $row['phone_number'] ?></td>
                    <td><?= $row['national_code'] ?></td>
                    <td><?= $row['request_type'] ?></td>
                    <td><?= $row['registration_date'] ?></td>
                    <?php for ($i = 1; $i <= 10; $i++) {
                        $dateKey = "date$i";
                        $resolvedKey = "resolved$i";
                        $fileKey = "file$i";
                        $expertKey = "expert$i";
                        $jahadFileKey = "jahad$i";

                        $highlight = '';
                        $checked = '';
                        $uploadSection = '';
                        $downloadButton = '';

                        if (!empty($row[$dateKey])) {
                            $gregorian = convertJalaliToGregorian($row[$dateKey]);
                            $diff = dateDiffInDays($gregorian, $currentDate);

                            if (!empty($row[$fileKey])) {
                                $highlight = "uploaded";
                                $downloadButton = "
                                    <a href='k_uploads/{$row[$fileKey]}' target='_blank' class='btn btn-sm btn-light mt-1'>مشاهده گزارش</a>
                                    <form method='post' action='delete_report_or_jahad.php' class='delete-report-form d-inline' style='display:inline-block;' onsubmit='return confirm(\"آیا مطمئن هستید که می‌خواهید گزارش را حذف کنید؟\")'>
                                        <input type='hidden' name='delete_report' value='1'>
                                        <input type='hidden' name='id' value='{$row['id']}'>
                                        <input type='hidden' name='step' value='$i'>
                                        <button type='submit' class='btn btn-sm btn-danger mt-1 ms-1'>حذف گزارش</button>
                                    </form>";
                            } elseif ($row[$resolvedKey] == 1) {
                                $highlight = "resolved";
                                $checked = "checked";
                                $uploadSection = "
                                    <form method='post' enctype='multipart/form-data' class='upload-form' data-id='{$row['id']}' data-step='$i'>
                                        <input type='file' name='upload_file' required>
                                        <input type='text' name='expert_name' placeholder='نام کارشناس' class='form-control mt-1' required>
                                        <button type='submit' class='btn btn-success btn-sm mt-1'>آپلود گزارش</button>
                                    </form>";
                            } elseif ($diff < 0) {
                                $highlight = "expired";
                            }


                            echo "<td class='$highlight' id='cell-{$row['id']}-$i'>";
                            echo $row[$dateKey];
                            // نمایش چک‌باکس فقط وقتی که گزارش و نامه جهاد موجود نباشند
                            if (empty($row[$fileKey]) && empty($row[$jahadFileKey])) {
                                echo "<br><input type='checkbox' data-id='{$row['id']}' data-step='$i' class='resolve-checkbox' $checked>";
                            }

                            echo $uploadSection;
                            echo $downloadButton;
                            // نمایش نام کارشناس اگر وجود داشت
                            if (!empty($row[$expertKey])) {
                                echo "<div class='expert-box'>کارشناس: " . htmlspecialchars($row[$expertKey]) . "</div>";
                            }


                            echo "<br>";

                            // قسمت مربوط به آپلود نامه جهاد
                            if (!empty($row[$jahadFileKey])) {
                                echo "
                                    <a href='{$row[$jahadFileKey]}' target='_blank' class='btn btn-sm btn-light mt-1'>مشاهده نامه جهاد</a>
                                    <form method='post' action='delete_report_or_jahad.php' class='delete-jahad-form d-inline' style='display:inline-block;' onsubmit='return confirm(\"آیا مطمئن هستید که می‌خواهید نامه جهاد را حذف کنید؟\")'>
                                        <input type='hidden' name='delete_jahad' value='1'>
                                        <input type='hidden' name='id' value='{$row['id']}'>
                                        <input type='hidden' name='step' value='$i'>
                                        <button type='submit' class='btn btn-sm btn-danger mt-1 ms-1'>حذف نامه</button>
                                    </form>";
                            } else {
                                echo "<form method='post' enctype='multipart/form-data' class='jahad-upload-form' data-id='{$row['id']}' data-step='$i'>
                                        <input type='file' name='jahad_file' required>
                                        <button type='submit' class='btn btn-warning btn-sm mt-1'>آپلود نامه جهاد</button>
                                    </form>";
                            }

                            
                            // قسمت رادیوباتن تغییر کاربری
                            $taghirKey = "taghir$i";
                            $hasTaghir = $row[$taghirKey] === "دارد" ? "checked" : "";
                            $noTaghir = $row[$taghirKey] === "ندارد" ? "checked" : "";
                            
                            echo "
                                <div class='mt-1'>
                                    <label>تغییر کاربری:</label><br>
                                    <label><input type='radio' name='taghir_{$row['id']}_$i' value='دارد' class='taghir-radio' data-id='{$row['id']}' data-step='$i' $hasTaghir> دارد</label>
                                    <label class='ms-2'><input type='radio' name='taghir_{$row['id']}_$i' value='ندارد' class='taghir-radio' data-id='{$row['id']}' data-step='$i' $noTaghir> ندارد</label>
                                </div>";
                            
                            // نمایش لینک Google Earth
                            if (!empty($row['kml_path'])) {
                                echo "
                                    <div class='mt-1'>
                                        <a href='gen_kml.php?id={$row['id']}&step=$i' target='_blank' title='مشاهده موقعیت در Google Earth'>
                                            <i class='fas fa-globe fa-lg text-success'></i>
                                        </a>
                                    </div>";
                            }








                            echo "</td>";
                        } else {
                            echo "<td>-</td>";
                        }
                    } ?>
                    <td><?= $row['des'] ?></td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    <?php } else {
        echo "<p>هیچ اطلاعاتی موجود نیست.</p>";
    } ?>
</div>

<script>
document.querySelectorAll('.resolve-checkbox').forEach(box => {
    box.addEventListener('change', function () {
        const id = this.dataset.id;
        const step = this.dataset.step;
        const field = `resolved${step}`;
        const value = this.checked ? 1 : 0;

        fetch('update_status.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `id=${id}&field=${field}&value=${value}`
        }).then(res => res.text()).then(response => {
            const cell = document.getElementById(`cell-${id}-${step}`);
            cell.classList.remove('expired', 'resolved', 'uploaded');

            if (value === 1) {
                cell.classList.add('resolved');
                const uploadForm = `
                    <form method="post" enctype="multipart/form-data" class="upload-form" data-id="${id}" data-step="${step}">
                        <input type="file" name="upload_file" required>
                        <input type="text" name="expert_name" placeholder="نام کارشناس" class="form-control mt-1" required>
                        <button type="submit" class="btn btn-success btn-sm mt-1">آپلود گزارش</button>
                    </form>
                `;
                cell.innerHTML += uploadForm;
            }
        });
    });
});

document.querySelectorAll('.taghir-radio').forEach(radio => {
    radio.addEventListener('change', function () {
        const id = this.dataset.id;
        const step = this.dataset.step;
        const value = this.value;
        const field = `taghir${step}`;

        fetch('update_status.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `id=${id}&field=${field}&value=${encodeURIComponent(value)}`
        }).then(res => res.text()).then(response => {
            console.log('تغییر کاربری ذخیره شد:', response);
        });
    });
});


document.addEventListener('submit', function (e) {
    if (e.target.classList.contains('upload-form')) {
        e.preventDefault();
        const form = e.target;
        const id = form.dataset.id;
        const step = form.dataset.step;
        const formData = new FormData(form);
        formData.append('id', id);
        formData.append('step', step);

        fetch('upload_file.php', {
            method: 'POST',
            body: formData
        }).then(res => res.text()).then(response => {
            const cell = document.getElementById(`cell-${id}-${step}`);
            cell.classList.remove('resolved');
            cell.classList.add('uploaded');
            cell.querySelector('.upload-form').remove();
            cell.innerHTML += `<a href="k_uploads/${response}" target="_blank" class="btn btn-sm btn-light mt-1">مشاهده گزارش</a>`;
        });
    }

    if (e.target.classList.contains('jahad-upload-form')) {
        e.preventDefault();
        const form = e.target;
        const id = form.dataset.id;
        const step = form.dataset.step;
        const formData = new FormData(form);
        formData.append('id', id);
        formData.append('step', step);

        fetch('upload_jahad.php', {
            method: 'POST',
            body: formData
        }).then(res => res.text()).then(response => {
            const cell = document.getElementById(`cell-${id}-${step}`);
            cell.querySelector('.jahad-upload-form').remove();
            cell.innerHTML += `<a href="k_uploads/${response}" target="_blank" class="btn btn-sm btn-light mt-1">مشاهده نامه جهاد</a>`;
        });
    }
});

</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const searchInput = document.getElementById("searchInput");
    const requestFilter = document.getElementById("requestFilter");
    const stepFilter = document.getElementById("stepFilter");
    const colorFilter = document.getElementById("colorFilter");
    const expertNameFilter = document.getElementById("expertNameFilter");

    const columnFilters = document.querySelectorAll(".column-filter");
    const stageColorFilters = document.querySelectorAll(".stage-color-filter");

    // ✳️ استخراج مقادیر یکتا از هر ستون و پر کردن selectهای فیلتر ستونی
    function populateColumnFilters() {
        const table = document.querySelector("table");
        const rows = Array.from(table.querySelectorAll("tbody tr"));

        columnFilters.forEach(select => {
            const colIdx = parseInt(select.dataset.column, 10);
            const values = new Set();

            rows.forEach(row => {
                const cell = row.querySelectorAll("td")[colIdx];
                if (cell) {
                    const txt = cell.textContent.trim();
                    if (txt) values.add(txt);
                }
            });

            // حذف گزینه‌های قبلی به‌جز "همه"
            const existingOptions = Array.from(select.options).slice(1);
            existingOptions.forEach(opt => opt.remove());

            // افزودن مقادیر یکتا
            Array.from(values).sort().forEach(val => {
                const opt = document.createElement("option");
                opt.value = val;
                opt.textContent = val;
                select.appendChild(opt);
            });
        });
    }

    function applyAllFilters() {
        const search = searchInput?.value?.toLowerCase() || "";
        const request = requestFilter?.value || "";
        const step = stepFilter?.value || "";
        const color = colorFilter?.value || "";
        const expertName = expertNameFilter?.value?.toLowerCase() || "";

        const columnFilterValues = {};
        columnFilters.forEach(select => {
            const col = select.dataset.column;
            const val = select.value.trim().toLowerCase();
            if (val) columnFilterValues[col] = val;
        });

        const stageFilters = {};
        stageColorFilters.forEach(select => {
            const step = select.dataset.step;
            const val = select.value;
            if (val) stageFilters[step] = val;
        });

        document.querySelectorAll("table tbody tr").forEach(row => {
            const id = row.dataset.id;
            let match = true;

            // جستجوی عمومی
            if (search && !row.innerText.toLowerCase().includes(search)) match = false;

            // نوع درخواست
            if (request && row.cells[5].innerText.trim() !== request) match = false;

            // نام کارشناس
            if (expertName && !row.innerText.toLowerCase().includes(expertName)) match = false;

            // فیلتر رنگ کلی با مرحله خاص
            if (color) {
                if (step) {
                    const cell = document.getElementById(`cell-${id}-${step}`);
                    if (!cell || !cell.classList.contains(color)) match = false;
                } else {
                    let found = false;
                    for (let i = 1; i <= 10; i++) {
                        const cell = document.getElementById(`cell-${id}-${i}`);
                        if (cell && cell.classList.contains(color)) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) match = false;
                }
            }

            // فیلتر رنگ مرحله‌ای
            for (const [stepNum, desiredClass] of Object.entries(stageFilters)) {
                const cell = document.getElementById(`cell-${id}-${stepNum}`);
                if (!cell || !cell.classList.contains(desiredClass)) {
                    match = false;
                    break;
                }
            }

            // فیلترهای ستونی
            for (const [col, val] of Object.entries(columnFilterValues)) {
                const cellText = row.querySelectorAll("td")[col]?.textContent.trim().toLowerCase();
                if (cellText !== val) {
                    match = false;
                    break;
                }
            }

            row.style.display = match ? "" : "none";
        });
    }

    // اول مقادیر یکتا را برای select فیلترها از جدول استخراج کن
    populateColumnFilters();

    // اتصال فیلترها به تابع اصلی
    [searchInput, requestFilter, stepFilter, colorFilter, expertNameFilter, ...columnFilters, ...stageColorFilters].forEach(el => {
        el?.addEventListener("input", applyAllFilters);
        el?.addEventListener("change", applyAllFilters);
    });

    // اجرای اولیه
    applyAllFilters();
});
</script>
<script>
function renumberRows() {
    const visibleRows = document.querySelectorAll("tbody tr");
    let count = 1;
    visibleRows.forEach(row => {
        if (row.style.display !== "none") {
            const cell = row.querySelector(".row-index");
            if (cell) cell.textContent = count++;
        }
    });
}

// در صورت وجود فیلترهای ورودی (مثل سرچ و دراپ‌داون‌ها)، هنگام تغییر آن‌ها شمارش را به‌روزرسانی کن:
document.querySelectorAll("#searchInput, #requestFilter, #stepFilter, #colorFilter, #expertNameFilter, .column-filter, .stage-color-filter").forEach(input => {
    input.addEventListener("input", () => {
        setTimeout(renumberRows, 100);  // کمی تأخیر برای اعمال فیلتر
    });

    input.addEventListener("change", () => {
        setTimeout(renumberRows, 100);
    });
});

// در صورت استفاده از فیلترهای خاص با جاوااسکریپت دستی، اطمینان حاصل کن که بعد از فیلتر، تابع renumberRows اجرا می‌شود.
</script>




</body>
</html>
