<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- Facility Check ----------------
if (!isset($_SESSION['facility_id'])) {
    die("Facility not set");
}
$facility_id = (int) $_SESSION['facility_id'];

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Fetch Products ----------------
$stmt = $pdo->prepare("SELECT * FROM products WHERE facility_id=? ORDER BY id DESC");
$stmt->execute([$facility_id]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Fetch Insurance Partners (enabled & for this facility) ----------------
$stmt = $pdo->prepare("
    SELECT ip.id, ip.name 
    FROM insurance_partners ip
    WHERE ip.status='enabled' AND ip.facility_id=?
    ORDER BY ip.name ASC
");
$stmt->execute([$facility_id]);
$insurancePartners = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- ENABLE / DISABLE PRODUCT ----------------
if (isset($_POST['toggle']) && $_POST['csrf'] == $csrf) {
    $newStatus = ($_POST['current_status'] == "enabled") ? "disabled" : "enabled";
    $update = $pdo->prepare("UPDATE products SET status=? WHERE id=? AND facility_id=?");
    $update->execute([$newStatus, $_POST['id'], $facility_id]);

    $_SESSION['flash'] = [
        "message" => "Product status updated!",
        "color" => "#17a2b8"
    ];
    header("Location: products.php");
    exit;
}

// ---------------- Fetch all insurance prices for all products ----------------
$stmt = $pdo->prepare("
    SELECT pip.* 
    FROM product_insurance_prices pip
    JOIN products p ON p.id = pip.product_id
    WHERE p.facility_id=?
");
$stmt->execute([$facility_id]);
$allPrices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Map product_id => [insurance_id => price]
$productPrices = [];
foreach($allPrices as $row){
    $productPrices[$row['product_id']][$row['insurance_partner_id']] = $row['price'];
}
?>



<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>

<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
    <div class="content-wrapper">
        <div class="col-xs-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="card-title">Medical Product Tariffs</h4>
                    <a href="add_product.php" class="btn btn-outline-primary btn-md">
                        <i class="icon-plus-circle"></i> Add Product
                    </a>
                </div>

                <div class="card-body collapse in">
                    <div class="card-block card-dashboard">
                        <div class="table-responsive">
                        <table class="table table-hover mb-0" id="Table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Insurance Prices</th>
                                    <th>Category Type</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

                            <tbody>
                            <?php foreach ($products as $p): ?>
                                <tr>
                                    <td><?= htmlspecialchars($p['name']) ?></td>

                                    <td>
                                        <button class="btn btn-sm btn-outline-info" onclick="document.getElementById('priceModal<?= $p['id'] ?>').style.display='block'">
                                            View Prices
                                        </button>

                                        <!-- Prices Modal -->
                                        <div id="priceModal<?= $p['id'] ?>" class="modal-custom" style="display:none;">
                                            <div class="modal-content-custom">
                                                <div class="modal-header-custom">
                                                    <h4>Insurance Prices for <?= htmlspecialchars($p['name']) ?></h4>
                                                    <span onclick="document.getElementById('priceModal<?= $p['id'] ?>').style.display='none'" class="close-custom">&times;</span>
                                                </div>
                                                <div class="modal-body-custom">
                                                    <?php
                                                    if(isset($productPrices[$p['id']]) && !empty($productPrices[$p['id']])){
                                                        foreach ($insurancePartners as $ins) {
                                                            $val = $productPrices[$p['id']][$ins['id']] ?? null;
                                                            echo "<strong>" . htmlspecialchars($ins['name']) . ":</strong> " 
                                                                 . ($val !== null ? number_format($val) . "RWF" : "—")
                                                                 . "<br>";
                                                        }
                                                    } else {
                                                        echo "No insurance prices set.";
                                                    }
                                                    ?>
                                                </div>
                                                <div class="modal-footer-custom">
                                                    <button onclick="document.getElementById('priceModal<?= $p['id'] ?>').style.display='none'" class="btn btn-secondary btn-sm">Close</button>
                                                </div>
                                            </div>
                                        </div>
                                    </td>

                                    <td>
                                        <?= ucfirst($p['category_type']) ?>
                                    </td>

                                    <td style="color: <?= $p['status']=='enabled'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                                        <?= ucfirst($p['status']) ?>
                                    </td>

                                    <td>
                                        <a href="edit_product.php?id=<?= $p['id'] ?>" 
                                           class="btn btn-sm btn-outline-primary">Edit</a>

                                        <form method="post" style="display:inline-block">
                                            <input type="hidden" name="csrf" value="<?= $csrf ?>">
                                            <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                            <input type="hidden" name="current_status" value="<?= $p['status'] ?>">

                                            <button name="toggle"
                                                class="btn btn-sm <?= $p['status']=='enabled'
                                                    ? 'btn-outline-danger black'
                                                    : 'btn-outline-success' ?>">
                                                <?= $p['status']=='enabled' ? 'Disable' : 'Enable' ?>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                        </div> <!-- table-responsive -->

                    </div>
                </div>

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

<style>
.modal-custom {
  position: fixed;
  z-index: 1050;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.5);
}
.modal-content-custom {
  background-color: #fff;
  margin: 10% auto;
  padding: 20px;
  border-radius: 5px;
  width: 400px;
}
.modal-header-custom { display:flex; justify-content:space-between; align-items:center; }
.close-custom { cursor:pointer; font-size:24px; font-weight:bold; }
.modal-body-custom { margin-top:10px; }
.modal-footer-custom { margin-top:15px; text-align:right; }
.toast-message {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    color: #fff;
    border-radius: 5px;
    z-index: 9999;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    font-size: 14px;
}
</style>

<script>
function showToast(message, color='#dc3545'){
    const t = document.createElement('div');
    t.className = 'toast-message';
    t.style.background = color;
    t.innerText = message;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 4000);
}

<?php if(isset($_SESSION['flash'])): ?>
showToast('<?= $_SESSION['flash']['message'] ?>', '<?= $_SESSION['flash']['color'] ?>');
<?php unset($_SESSION['flash']); endif; ?>
</script>

<?php include('includes/footer.php'); ?>
