<?php

use App\Core\Auth;

if (!($auth instanceof Auth) || !$auth->can('quality.manage')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى ضبط الجودة';
    return;
}

$qcTests = [];
$qcResults = [];
$tests = [];
$hasRuleViolated = false;
$tenantId = (int)($_SESSION['tenant_id'] ?? 1);
$tenantTestAnd = '';

try {
    $db->query('SELECT tenant_id FROM tests LIMIT 1');
    $tenantTestAnd = ' AND tenant_id = ' . (int)$tenantId;
} catch (Throwable $e) {}

try {
    $stmt = $db->query('SELECT id, name, test_code FROM tests WHERE 1=1' . $tenantTestAnd . ' ORDER BY name LIMIT 200');
    $tests = $stmt->fetchAll();
} catch (Throwable $e) {
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['create_qc_test'])) {
        $testId = (int)($_POST['test_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $level = trim($_POST['level'] ?? '');
        $mean = $_POST['target_mean'] ?? null;
        $sd = $_POST['target_sd'] ?? null;
        $unit = trim($_POST['unit'] ?? '');

        if ($testId > 0 && $name !== '') {
            $stmt = $db->prepare(
                'INSERT INTO qc_tests (test_id, name, level, target_mean, target_sd, unit)
                 VALUES (:test_id, :name, :level, :mean, :sd, :unit)'
            );
            $m = $mean === '' ? null : $mean;
            $s = $sd === '' ? null : $sd;
            $stmt->execute([
                'test_id' => $testId,
                'name' => $name,
                'level' => $level !== '' ? $level : null,
                'mean' => $m,
                'sd' => $s,
                'unit' => $unit !== '' ? $unit : null
            ]);
        }
    } elseif (isset($_POST['add_qc_result'])) {
        $qcTestId = (int)($_POST['qc_test_id'] ?? 0);
        $valueInput = $_POST['value'] ?? null;
        $note = trim($_POST['note'] ?? '');

        if ($qcTestId > 0 && $valueInput !== null && trim($valueInput) !== '') {
            $stmt = $db->prepare(
                'SELECT target_mean, target_sd FROM qc_tests WHERE id = :id'
            );
            $stmt->execute(['id' => $qcTestId]);
            $cfg = $stmt->fetch();

            $value = (float)str_replace(',', '.', $valueInput);
            $z = null;
            $status = 'in_range';
            $ruleViolated = null;

            if ($cfg && $cfg['target_mean'] !== null && $cfg['target_sd'] !== null && (float)$cfg['target_sd'] > 0) {
                $mean = (float)$cfg['target_mean'];
                $sd = (float)$cfg['target_sd'];
                $z = ($value - $mean) / $sd;

                // قواعد Westgard
                if (abs($z) > 3.0) {
                    $ruleViolated = '1-3s';
                    $status = 'out_of_range';
                } elseif (abs($z) > 2.0) {
                    $ruleViolated = '1-2s';
                    $status = 'out_of_range';
                } else {
                    $prev = $db->prepare('SELECT z_score FROM qc_results WHERE qc_test_id = ? ORDER BY run_datetime DESC LIMIT 2');
                    $prev->execute([$qcTestId]);
                    $prevResults = $prev->fetchAll();
                    if (count($prevResults) >= 1) {
                        $prevZ = (float)($prevResults[0]['z_score'] ?? 0);
                        if ($prevZ != 0 && abs($prevZ) > 2 && (($z > 2 && $prevZ > 2) || ($z < -2 && $prevZ < -2))) {
                            $ruleViolated = '2-2s';
                            $status = 'out_of_range';
                        } elseif (count($prevResults) >= 1 && abs($z - $prevZ) >= 4) {
                            $ruleViolated = 'R-4s';
                            $status = 'out_of_range';
                        }
                    }
                }
            }

            $insCols = 'qc_test_id, run_datetime, value, z_score, status, note, created_by';
            $insVals = ':qc_test_id, NOW(), :value, :z, :status, :note, :uid';
            $params = ['qc_test_id' => $qcTestId, 'value' => $value, 'z' => $z, 'status' => $status, 'note' => $note !== '' ? $note : null, 'uid' => $_SESSION['user_id'] ?? null];
            try {
                $db->query('SELECT rule_violated FROM qc_results LIMIT 1');
                $insCols .= ', rule_violated';
                $insVals .= ', :rule_violated';
                $params['rule_violated'] = $ruleViolated;
            } catch (Throwable $e) {}
            $stmt = $db->prepare("INSERT INTO qc_results ($insCols) VALUES ($insVals)");
            $stmt->execute($params);
        }
    }
}

try {
    $joinTenant = ($tenantTestAnd !== '') ? ' AND t.tenant_id = ' . (int)$tenantId . ' ' : '';
    $stmt = $db->query(
        'SELECT q.id, q.name, q.level, q.target_mean, q.target_sd, q.unit, t.name AS test_name
         FROM qc_tests q
         JOIN tests t ON t.id = q.test_id' . $joinTenant . '
         ORDER BY q.id DESC
         LIMIT 50'
    );
    $qcTests = $stmt->fetchAll();

    $stmt = $db->query(
        'SELECT r.id, r.run_datetime, r.value, r.z_score, r.status, r.note,
                q.name AS qc_name, q.id AS qc_test_id, q.target_mean, q.target_sd,
                t.name AS test_name
         FROM qc_results r
         JOIN qc_tests q ON q.id = r.qc_test_id
         JOIN tests t ON t.id = q.test_id' . $joinTenant . '
         ORDER BY r.run_datetime DESC
         LIMIT 100'
    );
    $qcResults = $stmt->fetchAll();
    $hasRuleViolated = false;
    try { $db->query('SELECT rule_violated FROM qc_results LIMIT 1'); $hasRuleViolated = true; } catch (Throwable $e) {}
    if ($hasRuleViolated) {
        $stmt2 = $db->query('SELECT r.id, r.rule_violated FROM qc_results r JOIN qc_tests q ON q.id = r.qc_test_id JOIN tests t ON t.id = q.test_id' . $joinTenant . ' ORDER BY r.run_datetime DESC LIMIT 100');
        $rvMap = [];
        foreach ($stmt2->fetchAll() as $row) $rvMap[(int)$row['id']] = $row['rule_violated'] ?? null;
        foreach ($qcResults as &$r) { $r['rule_violated'] = $rvMap[(int)$r['id']] ?? null; }
        unset($r);
    }
} catch (Throwable $e) {
}

$chartQcId = (int)($_GET['chart_qc'] ?? 0);
$chartData = [];
if ($chartQcId > 0) {
    try {
        $chartSql = 'SELECT r.run_datetime, r.value, r.z_score, q.target_mean, q.target_sd, q.name AS qc_name FROM qc_results r JOIN qc_tests q ON q.id = r.qc_test_id JOIN tests t ON t.id = q.test_id WHERE r.qc_test_id = ?';
        $chartParams = [$chartQcId];
        if ($tenantTestAnd !== '') {
            $chartSql .= ' AND t.tenant_id = ?';
            $chartParams[] = $tenantId;
        }
        $chartSql .= ' ORDER BY r.run_datetime ASC LIMIT 50';
        $stmt = $db->prepare($chartSql);
        $stmt->execute($chartParams);
        $chartData = $stmt->fetchAll();
    } catch (Throwable $e) {}
}
?>
<div class="page-header">
    <h1>ضبط الجودة</h1>
    <a href="index.php?page=dashboard" class="btn-secondary">الرئيسية</a>
</div>
<div class="section-card">
    <h3>تعريف اختبارات ضبط الجودة</h3>
    <form method="post" class="form-grid">
        <div>
            <label>الفحص</label>
            <select name="test_id" required>
                <option value="">اختر الفحص</option>
                <?php foreach ($tests as $t): ?>
                    <option value="<?php echo (int)$t['id']; ?>">
                        <?php echo htmlspecialchars($t['name'] . ' (' . $t['test_code'] . ')', ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>اسم برنامج QC</label>
            <input type="text" name="name" required>
        </div>
        <div>
            <label>المستوى</label>
            <input type="text" name="level" placeholder="Level 1 / Level 2">
        </div>
        <div>
            <label>المتوسط المستهدف</label>
            <input type="number" step="0.001" name="target_mean">
        </div>
        <div>
            <label>الانحراف المعياري</label>
            <input type="number" step="0.001" name="target_sd">
        </div>
        <div>
            <label>الوحدة</label>
            <input type="text" name="unit">
        </div>
        <div class="full-width form-actions">
            <button type="submit" name="create_qc_test" value="1">حفظ برنامج QC</button>
        </div>
    </form>
</div>
<div class="section-card">
    <h3>برامج ضبط الجودة المعرفة</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>الفحص</th>
                    <th>اسم البرنامج</th>
                    <th>المستوى</th>
                    <th>المتوسط</th>
                    <th>SD</th>
                    <th>الوحدة</th>
                    <th>مخطط</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($qcTests as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['test_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['level'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['target_mean'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['target_sd'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><a href="index.php?page=quality&chart_qc=<?php echo (int)$row['id']; ?>">Levey-Jennings</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="section-card">
    <h3>إدخال نتائج ضبط الجودة</h3>
    <form method="post" class="form-grid">
        <div>
            <label>برنامج QC</label>
            <select name="qc_test_id" required>
                <option value="">اختر البرنامج</option>
                <?php foreach ($qcTests as $row): ?>
                    <option value="<?php echo (int)$row['id']; ?>">
                        <?php echo htmlspecialchars($row['test_name'] . ' - ' . $row['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>القيمة المقاسة</label>
            <input type="number" step="0.001" name="value" required>
        </div>
        <div class="full-width">
            <label>ملاحظة</label>
            <input type="text" name="note">
        </div>
        <div class="full-width form-actions">
            <button type="submit" name="add_qc_result" value="1">حفظ النتيجة</button>
        </div>
    </form>
</div>
<?php if (count($chartData) > 0): ?>
<div class="section-card">
    <h3>مخطط Levey-Jennings — <?php echo htmlspecialchars($chartData[0]['qc_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></h3>
    <p><a href="index.php?page=quality">← العودة لضبط الجودة</a></p>
    <div style="max-width:900px;height:400px;margin:1rem 0;">
        <canvas id="leveyJenningsChart"></canvas>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
    (function(){
        var mean = <?php echo json_encode((float)($chartData[0]['target_mean'] ?? 0)); ?>;
        var sd = <?php echo json_encode((float)($chartData[0]['target_sd'] ?? 1)); ?>;
        var labels = <?php echo json_encode(array_map(function($r){ return date('m/d H:i', strtotime($r['run_datetime'])); }, $chartData)); ?>;
        var values = <?php echo json_encode(array_map(function($r){ return (float)$r['value']; }, $chartData)); ?>;
        var ctx = document.getElementById('leveyJenningsChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    { label: 'القيمة المقاسة', data: values, borderColor: '#2563eb', backgroundColor: 'rgba(37,99,235,0.1)', fill: false, tension: 0.2 },
                    { label: 'Mean', data: labels.map(function(){ return mean; }), borderColor: '#059669', borderDash: [2,2], fill: false },
                    { label: '+1SD', data: labels.map(function(){ return mean + sd; }), borderColor: '#d97706', borderDash: [4,4], fill: false },
                    { label: '-1SD', data: labels.map(function(){ return mean - sd; }), borderColor: '#d97706', borderDash: [4,4], fill: false },
                    { label: '+2SD', data: labels.map(function(){ return mean + 2*sd; }), borderColor: '#dc2626', borderDash: [2,2], fill: false },
                    { label: '-2SD', data: labels.map(function(){ return mean - 2*sd; }), borderColor: '#dc2626', borderDash: [2,2], fill: false },
                    { label: '+3SD', data: labels.map(function(){ return mean + 3*sd; }), borderColor: '#991b1b', borderDash: [1,1], fill: false },
                    { label: '-3SD', data: labels.map(function(){ return mean - 3*sd; }), borderColor: '#991b1b', borderDash: [1,1], fill: false }
                ]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'top' } }, scales: { y: { beginAtZero: false } } }
        });
    })();
    </script>
</div>
<?php endif; ?>
<div class="section-card">
    <h3>أحدث نتائج ضبط الجودة</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>التاريخ</th>
                    <th>الفحص</th>
                    <th>برنامج QC</th>
                    <th>القيمة</th>
                    <th>Z-Score</th>
                    <th>الحالة</th>
                    <?php if ($hasRuleViolated): ?><th>قاعدة Westgard</th><?php endif; ?>
                    <th>ملاحظة</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($qcResults as $r): ?>
                <tr>
                    <td><?php echo htmlspecialchars($r['run_datetime'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($r['test_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($r['qc_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($r['value'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($r['z_score'] !== null ? number_format((float)$r['z_score'], 2) : '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <?php if ($r['status'] === 'in_range'): ?>
                            <span class="badge badge-completed">ضمن المدى</span>
                        <?php else: ?>
                            <span class="badge badge-cancelled">خارج المدى</span>
                        <?php endif; ?>
                    </td>
                    <?php if ($hasRuleViolated): ?><td><?php echo htmlspecialchars($r['rule_violated'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td><?php endif; ?>
                    <td><?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
