<?php
include getenv("DOCUMENT_ROOT")."/include/session_include.php";

$c_uid = $_POST["c_uid"] ?? $_GET["c_uid"] ?? "";
$note_page = intval($_POST["note_page"] ?? 1);
$oil_page  = intval($_POST["oil_page"] ?? 1);
$co_visit_page = intval($_POST["co_visit_page"] ?? 1);

if ($c_uid == "") {
    echo "Invalid data. [Err - c_uid / FORECAST-POPUP]";
    exit();
}

/* 날짜 포맷 함수 */
function onlyDate($str) {
    if (!$str || strlen($str) < 8) return "";
    return substr($str, 0, 4) . "-" . substr($str, 4, 2) . "-" . substr($str, 6, 2);
}

/*-----------------------------------
    고객 기본 정보
------------------------------------*/
$customerQuery = "
    SELECT *
    FROM tbl_customer
    WHERE c_uid = '$c_uid'
";
$customerResult = $jdb->nQuery($customerQuery, "customer query error");
$firstRow = mysqli_fetch_array($customerResult, MYSQLI_ASSOC);

// $c_nameSTR = htmlspecialchars($firstRow['c_name'], ENT_QUOTES);
$c_commentSTR = htmlspecialchars($firstRow['c_comment_ri'], ENT_QUOTES);


/*-----------------------------------
    NOTE 데이터
------------------------------------*/
$notesPerPage = 3;

// 전체 개수 조회
$noteCountQuery = "
    SELECT COUNT(*) AS total
    FROM tbl_note
    WHERE n_customeruid = '$c_uid'
";
$noteCountResult = $jdb->nQuery($noteCountQuery, "note count error");
$noteCount = mysqli_fetch_array($noteCountResult, MYSQLI_ASSOC)['total'];

$totalNotePages = ceil($noteCount / $notesPerPage);
if ($note_page < 1) $note_page = 1;
$note_start = ($note_page - 1) * $notesPerPage;

// NOTE 조회
$noteQuery = "
    SELECT *
    FROM tbl_customer tc
    LEFT OUTER JOIN tbl_note tn ON tc.c_uid = tn.n_customeruid
    LEFT OUTER JOIN tbl_member tm ON tn.n_memberuid = tm.m_uid
    WHERE tc.c_uid = '$c_uid' and tn.n_status = 'A'
    ORDER BY tn.n_createddate DESC
    LIMIT $note_start, $notesPerPage
";
$noteResult = $jdb->nQuery($noteQuery, "note query error");


/*-----------------------------------
    OIL HISTORY 데이터
------------------------------------*/
$oilPerPage = 10;

// 전체 개수 조회
$oilCountQuery = "
    SELECT COUNT(*) AS total
    FROM tbl_daily
    WHERE d_customeruid = '$c_uid'
      AND d_status = 'F'
";
$oilCountResult = $jdb->nQuery($oilCountQuery, "oil count error");
$oilCount = mysqli_fetch_array($oilCountResult, MYSQLI_ASSOC)['total'];

$totalOilPages = ceil($oilCount / $oilPerPage);
if ($oil_page < 1) $oil_page = 1;
$oil_start = ($oil_page - 1) * $oilPerPage;

// 데이터 조회
$oilQuery = "
    SELECT d_visitdate, d_quantity, m_initial, d_payamount, d_paymenttype, d_paynote, d_paystatus
    FROM tbl_daily td
    LEFT OUTER JOIN tbl_request tr ON td.d_ruid = tr.r_uid
    LEFT OUTER JOIN tbl_member tm ON td.d_driveruid = tm.m_uid
    WHERE td.d_customeruid = '$c_uid'
      AND td.d_status = 'F'
    ORDER BY td.d_visitdate DESC
    LIMIT $oil_start, $oilPerPage
";
$oilResult = $jdb->nQuery($oilQuery, "oil query error");

/*-----------------------------------
    CO-VISIT 데이터
------------------------------------*/
$coPerPage = 5;

$coCountQuery = "
    SELECT COUNT(*) AS total
    FROM tbl_co_visit
    WHERE cv_customer_uid = '$c_uid'
";
$coCountResult = $jdb->nQuery($coCountQuery, "co count error");
$coCount = mysqli_fetch_array($coCountResult, MYSQLI_ASSOC)['total'];

$totalCoPages = ceil($coCount / $coPerPage);
if ($co_visit_page < 1) $co_visit_page = 1;
$co_start = ($co_visit_page - 1) * $coPerPage;

$coQuery = "
    SELECT cv.*, tc.c_name AS co_name, tc.c_accountno AS co_accountno
    FROM tbl_co_visit cv
    LEFT JOIN tbl_customer tc ON cv.cv_co_customer_uid = tc.c_uid
    WHERE cv.cv_customer_uid = '$c_uid'
    ORDER BY cv.cv_score DESC
    LIMIT $co_start, $coPerPage
";
$coResult = $jdb->nQuery($coQuery, "co query error");

?>

<div class="rightinfo-container">

    <!-- COMENT SECTION -->
    <h3 class="rightinfo-title">Comment</h3>
    <div class="rightinfo-value"><?= nl2br($c_commentSTR) ?></div>

    <!-- NOTE SECTION -->
    <h3 class="note-title">Note</h3>

    <table class="note-table">
        <tr>
            <th>Date</th>
            <th>Note</th>
        </tr>

        <?php while ($note = mysqli_fetch_array($noteResult, MYSQLI_ASSOC)) {
            $date = onlyDate($note['n_createddate']);
            $txt  = nl2br(htmlspecialchars($note['n_note'], ENT_QUOTES));

            echo "
            <tr>
                <td class='td-date'>$date</td>
                <td class='td-note'>$txt</td>
            </tr>";
        } ?>
    </table>

    <div class="pagination">
        <?php
        $blockSize = 5;
        $noteBlock = ceil($note_page / $blockSize);
        $noteStart = ($noteBlock - 1) * $blockSize + 1;
        $noteEnd = min($noteStart + $blockSize - 1, $totalNotePages);

        if ($noteStart > 1) {
            echo "<a class='page-btn arrow' href='#' onclick='loadNotePage(\"$c_uid\", ".($noteStart-1)."); return false;'>&laquo;</a>";
        }

        for ($i = $noteStart; $i <= $noteEnd; $i++) {
            $act = ($i == $note_page) ? "active" : "";
            echo "<a class='page-btn $act' href='#' onclick='loadNotePage(\"$c_uid\", $i); return false;'>$i</a>";
        }

        if ($noteEnd < $totalNotePages) {
            echo "<a class='page-btn arrow' href='#' onclick='loadNotePage(\"$c_uid\", ".($noteEnd+1)."); return false;'>&raquo;</a>";
        }
        ?>
    </div>

    <!-- OIL HISTORY SECTION -->
    <h3 class="note-title">Oil History</h3>

    <table class="note-table">
        <tr>
            <th>Date</th>
            <th>Quantity</th>
            <th>Paid (Cash)</th>
        </tr>

        <?php while ($oil = mysqli_fetch_array($oilResult, MYSQLI_ASSOC)) {
            $date = onlyDate($oil['d_visitdate']);
            $qty  = number_format($oil['d_quantity']);
            $drv  = $oil['m_initial'] ?: "-";

            $amount = isset($oil['d_payamount']) ? $oil['d_payamount'] : "";
            $paymentType = $oil['d_paymenttype'] ?? "";
            $payNote = trim($oil['d_paynote'] ?? "");

            if ($oil['d_paystatus'] === "P") {
                $pay = "Paid ($" . $amount . ")";
            } else {
                if ($paymentType === "CA") {
                    $pay = "Unpaid";
                } else {
                    if ($payNote !== "") {
                        // 특수문자 처리
                        $pay = htmlspecialchars($payNote, ENT_QUOTES);
                    } else {
                        $pay = "";
                    }
                }
            }


            echo "
            <tr>
                <td class='td-date'>$date</td>
                <td class='td-qty'>$qty</td>
                <td class='td-pay'>$pay</td>
            </tr>";
        } ?>
    </table>

    <div class="pagination">
        <?php
        $oilBlock = ceil($oil_page / $blockSize);
        $oilStart = ($oilBlock - 1) * $blockSize + 1;
        $oilEnd = min($oilStart + $blockSize - 1, $totalOilPages);

        if ($oilStart > 1) {
            echo "<a class='page-btn arrow' href='#' onclick='loadOilPage(\"$c_uid\", ".($oilStart-1)."); return false;'>&laquo;</a>";
        }

        for ($i = $oilStart; $i <= $oilEnd; $i++) {
            $act = ($i == $oil_page) ? "active" : "";
            echo "<a class='page-btn $act' href='#' onclick='loadOilPage(\"$c_uid\", $i); return false;'>$i</a>";
        }

        if ($oilEnd < $totalOilPages) {
            echo "<a class='page-btn arrow' href='#' onclick='loadOilPage(\"$c_uid\", ".($oilEnd+1)."); return false;'>&raquo;</a>";
        }
        ?>
    </div>

    <!-- CO-VISIT -->
    <!-- <h3 class="note-title">Recomendation</h3>

    <table class="note-table">
        <tr>
            <th>Account</th>
            <th>Customer</th>
            <th>Last CoVisit</th>
            <th>Distance</th>
            <th>CoVisit %</th>
        </tr>

        <?php while ($co = mysqli_fetch_array($coResult, MYSQLI_ASSOC)) {
            $last = $co['cv_last_co_visit_date'] ?: "-";

            $co_total = $co['cv_visit_count'];
            $co_match = $co['cv_co_visit_count'];

            $percent = ($co_total > 0) ? round(($co_match / $co_total) * 100, 1) : 0;

            echo "
            <tr>
                <td style='width:80px;'>{$co['co_accountno']}</td>
                <td style='width:100px;'>{$co['co_name']}</td>
                <td style='width:100px; text-align:center;'>{$last}</td>
                <td style='width:50px; text-align:right;'>{$co['cv_distance']} km</td>
                <td style='width:80px; text-align:right;'>{$percent} %</td>
            </tr>";
        } ?>
    </table>

    <div class="pagination">
        <?php
        $coBlock = ceil($co_visit_page / $blockSize);
        $coStart = ($coBlock - 1) * $blockSize + 1;
        $coEnd   = min($coStart + $blockSize - 1, $totalCoPages);

        if ($coStart > 1) {
            echo "<a class='page-btn arrow' href='#' onclick='loadCoVisitPage(\"$c_uid\", ".($coStart-1)."); return false;'>&laquo;</a>";
        }

        for ($i = $coStart; $i <= $coEnd; $i++) {
            $act = ($i == $co_visit_page) ? "active" : "";
            echo "<a class='page-btn $act' href='#' onclick='loadCoVisitPage(\"$c_uid\", $i); return false;'>$i</a>";
        }

        if ($coEnd < $totalCoPages) {
            echo "<a class='page-btn arrow' href='#' onclick='loadCoVisitPage(\"$c_uid\", ".($coEnd+1)."); return false;'>&raquo;</a>";
        }
        ?>
    </div> -->
</div>

<script>
function loadNotePage(c_uid, page) {
    $.ajax({
        url: "/lib/shortInfo_right_lib.php",
        type: "POST",
        data: { c_uid: c_uid, note_page: page },
        success: function(res) {
            $(".rightinfo-container").parent().html(res);
        }
    });
}

function loadOilPage(c_uid, page) {
    $.ajax({
        url: "/lib/shortInfo_right_lib.php",
        type: "POST",
        data: { c_uid: c_uid, oil_page: page },
        success: function(res) {
            $(".rightinfo-container").parent().html(res);
        }
    });
}

function loadCoVisitPage(c_uid, page) {
    $.ajax({
        url: "/lib/shortInfo_right_lib.php",
        type: "POST",
        data: { c_uid: c_uid, co_visit_page: page },
        success: function(res) {
            $(".rightinfo-container").parent().html(res);
        }
    });
}
</script>


<style>
.rightinfo-container {
    padding: 5px;
    font-size: 15px;
    line-height: 1.5;
}

.rightinfo-title, .note-title {
    font-size: 17px;
    font-weight: 600;
    border-bottom: 1px solid #2A9B56;
}

.note-title {
    margin-top: 20px;
}

.note-table {
    width: 100%;
    font-size: 14px;
}

.note-table th {
    background: #2A9B56;
    color: white;
    padding: 5px;
    border: 1px solid #ddd;
    text-align: center;
}

.note-table td {
    padding: 5px;
    border: 1px solid #ddd;
    vertical-align: top;
}

.td-date { width: 20%; }

.note-table tr:nth-child(even) {
    background: #f6f6f6;
}

.pagination {
    text-align: center;
    margin: 10px 0 10px 0;
}

.page-btn {
    display: inline-block;
    padding: 5px 7px;
    margin: 0 3px;
    border: 1px solid #2A9B56;
    color: #2A9B56;
    text-decoration: none;
    border-radius: 5px;
    font-size: 13px;
}

.page-btn.active,
.page-btn:hover {
    background: #2A9B56;
    color: white;
}

.page-btn.arrow {
    font-weight: bold;
    padding: 6px 14px;
}
</style>
