<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

$prodcode = isset($_POST['prodcode']) ? $_POST['prodcode'] : '';
$itemname = isset($_POST['itemname']) ? $_POST['itemname'] : '';
$spec = isset($_POST['spec']) ? $_POST['spec'] : '';
$remarks = isset($_POST['remarks']) ? $_POST['remarks'] : '';
$fromdate = isset($_POST['fromdate']) ? $_POST['fromdate'] : '';
$todate = isset($_POST['todate']) ? $_POST['todate'] : '';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$title_message = '수불내역 상세';

// 입고 내역 조회
$in_sql = "SELECT 
                lot_no,
                inspection_date,
                supplier,
                received_qty,
                unit,
                material_no,
                manufacturer,
                remarks,
                purchase_price_excl_vat,
                weight_kg
            FROM {$DB}.instock 
            WHERE prodcode = ? 
            AND inspection_date BETWEEN date(?) AND date(?)
            AND is_deleted IS NULL
            ORDER BY inspection_date DESC";

// 사용 내역 조회 (usage 테이블이 있을 경우 사용, 없으면 빈 배열)
$out_records = array();
try {
    // usage 테이블 존재 여부 확인
    $check_table_sql = "SHOW TABLES LIKE '{$DB}.usage'";
    $check_stmh = $pdo->query($check_table_sql);
    
    if ($check_stmh->rowCount() > 0) {
        // usage 테이블이 존재하는 경우
        $out_sql = "SELECT 
                        usage_date,
                        usage_qty,
                        unit,
                        usage_reason,
                        remarks
                    FROM {$DB}.usage 
                    WHERE prodcode = ? 
                    AND usage_date BETWEEN date(?) AND date(?)
                    AND is_deleted IS NULL
                    ORDER BY usage_date DESC";
        
        $out_stmh = $pdo->prepare($out_sql);
        $out_stmh->bindValue(1, $prodcode, PDO::PARAM_STR);
        $out_stmh->bindValue(2, $fromdate, PDO::PARAM_STR);
        $out_stmh->bindValue(3, $todate, PDO::PARAM_STR);
        $out_stmh->execute();
        $out_records = $out_stmh->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // 입고 내역 조회
    $in_stmh = $pdo->prepare($in_sql);
    $in_stmh->bindValue(1, $prodcode, PDO::PARAM_STR);
    $in_stmh->bindValue(2, $fromdate, PDO::PARAM_STR);
    $in_stmh->bindValue(3, $todate, PDO::PARAM_STR);
    $in_stmh->execute();
    $in_records = $in_stmh->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    echo "오류: " . $e->getMessage();
    exit;
}
?>

<div class="container-fluid">
    <div class="d-flex align-items-center justify-content-center">
        <div class="card justify-content-center" style="width: 100%;">
            <div class="card-header text-center">
                <span class="text-center fs-5 me-3"><?=$title_message?></span>
                <button type="button" id="closeBtn" class="btn btn-secondary btn-sm float-end me-2">닫기</button>
                <button type="button" class="close float-end" style="background: none; border: none; font-size: 1.5rem; color: #000;">&times;</button>
            </div>
            <div class="card-body">
                <!-- 품목 정보 -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <strong>품목코드:</strong> <?= htmlspecialchars($prodcode) ?> | 
                            <strong>품목명:</strong> <?= htmlspecialchars($itemname) ?> | 
                            <strong>규격:</strong> <?= htmlspecialchars($spec) ?> | 
                            <strong>비고:</strong> <?= htmlspecialchars($remarks) ?>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- 입고 내역 -->
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0">입고 내역 (<?= count($in_records) ?>건)</h6>
                            </div>
                            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                                <?php if (count($in_records) > 0): ?>
                                    <table class="table table-sm table-striped">
                                        <thead class="table-light">
                                            <tr>
                                                <th>로트번호</th>
                                                <th>입고일</th>
                                                <th>업체</th>
                                                <th>수량</th>
                                                <th>단위</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($in_records as $record): ?>
                                                <tr>
                                                    <td class="fw-bold text-primary"><?= htmlspecialchars($record['lot_no']) ?></td>
                                                    <td><?= htmlspecialchars($record['inspection_date']) ?></td>
                                                    <td><?= htmlspecialchars($record['supplier']) ?></td>
                                                    <td class="text-end fw-bold text-success">
                                                        <?php if (is_numeric($record['received_qty'])) : ?>
                                                            <?= number_format($record['received_qty']) ?>
                                                        <?php else : ?>
                                                            <?= htmlspecialchars($record['received_qty']) ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?= htmlspecialchars($record['unit']) ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                <?php else: ?>
                                    <div class="text-center text-muted">
                                        <p>입고 내역이 없습니다.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 사용 내역 -->
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-danger text-white">
                                <h6 class="mb-0">사용 내역 (<?= count($out_records) ?>건)</h6>
                            </div>
                            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                                <?php if (count($out_records) > 0): ?>
                                    <table class="table table-sm table-striped">
                                        <thead class="table-light">
                                            <tr>
                                                <th>사용일</th>
                                                <th>사용량</th>
                                                <th>단위</th>
                                                <th>사용사유</th>
                                                <th>비고</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($out_records as $record): ?>
                                                <tr>
                                                    <td><?= htmlspecialchars($record['usage_date']) ?></td>
                                                    <td class="text-end fw-bold text-danger">
                                                        <?php if (is_numeric($record['usage_qty'])) : ?>
                                                            <?= number_format($record['usage_qty']) ?>
                                                        <?php else : ?>
                                                            <?= htmlspecialchars($record['usage_qty']) ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?= htmlspecialchars($record['unit']) ?></td>
                                                    <td><?= htmlspecialchars($record['usage_reason']) ?></td>
                                                    <td><?= htmlspecialchars($record['remarks']) ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                <?php else: ?>
                                    <div class="text-center text-muted">
                                        <p>사용 내역이 없습니다.<br><small>(사용량 테이블이 설정되지 않았거나 해당 기간에 사용 내역이 없습니다.)</small></p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 요약 정보 -->
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0">재고 요약</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="text-center">
                                            <h5 class="text-success">총 입고량</h5>
                                            <h4 class="text-success">
                                                <?php 
                                                $total_in = 0;
                                                foreach ($in_records as $record) {
                                                    if (is_numeric($record['received_qty'])) {
                                                        $total_in += $record['received_qty'];
                                                    }
                                                }
                                                echo number_format($total_in);
                                                ?>
                                            </h4>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="text-center">
                                            <h5 class="text-danger">총 사용량</h5>
                                            <h4 class="text-danger">
                                                <?php 
                                                $total_out = 0;
                                                foreach ($out_records as $record) {
                                                    if (is_numeric($record['usage_qty'])) {
                                                        $total_out += $record['usage_qty'];
                                                    }
                                                }
                                                echo number_format($total_out);
                                                ?>
                                            </h4>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="text-center">
                                            <h5 class="text-primary">현재 재고</h5>
                                            <h4 class="text-primary">
                                                <?= number_format($total_in - $total_out) ?>
                                            </h4>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="text-center">
                                            <h5 class="text-info">조회기간</h5>
                                            <h6 class="text-info">
                                                <?= $fromdate ?> ~ <?= $todate ?>
                                            </h6>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>