<?php
require_once __DIR__ . '/includes/app.php';
require_login();
require_roles(['Admin Audit', 'Pentadbir Sistem']);

$auditId = (int) ($_POST['audit_id'] ?? 0);
$assignedUnit = trim((string) ($_POST['assigned_unit'] ?? ''));
$approvalStatus = (string) ($_POST['audit_approval_status'] ?? '');
$allowedStatuses = ['perlu_kemaskini', 'lulus_diaudit'];

if ($auditId <= 0 || $assignedUnit === '' || !in_array($approvalStatus, $allowedStatuses, true)) {
    header('Location: dashboard.php');
    exit();
}

$assignmentStmt = $conn->prepare("
    SELECT id
    FROM audit_form_assignments
    WHERE audit_form_id = ? AND assigned_unit = ?
    LIMIT 1
");
$assignmentStmt->bind_param('is', $auditId, $assignedUnit);
$assignmentStmt->execute();
$assignment = $assignmentStmt->get_result()->fetch_assoc();

if (!$assignment) {
    header('Location: dashboard.php');
    exit();
}

if ($approvalStatus === 'lulus_diaudit') {
    $feedbackStmt = $conn->prepare("
        SELECT id
        FROM audit_feedbacks
        WHERE audit_form_id = ? AND submitted_unit = ?
        LIMIT 1
    ");
    $feedbackStmt->bind_param('is', $auditId, $assignedUnit);
    $feedbackStmt->execute();

    if (!$feedbackStmt->get_result()->fetch_assoc()) {
        header('Location: dashboard.php?error=audit_approval_incomplete');
        exit();
    }
}

$stmt = $conn->prepare("
    UPDATE audit_form_assignments
    SET audit_approval_status = ?
    WHERE audit_form_id = ? AND assigned_unit = ?
    LIMIT 1
");
$stmt->bind_param('sis', $approvalStatus, $auditId, $assignedUnit);
$stmt->execute();

$summaryStmt = $conn->prepare("
    SELECT
        COUNT(*) AS total_assignments,
        SUM(audit_approval_status = 'lulus_diaudit') AS total_approved
    FROM audit_form_assignments
    WHERE audit_form_id = ?
");
$summaryStmt->bind_param('i', $auditId);
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc();
$overallStatus = ((int) ($summary['total_assignments'] ?? 0) > 0
    && (int) ($summary['total_assignments'] ?? 0) === (int) ($summary['total_approved'] ?? 0))
    ? 'lulus_diaudit'
    : 'perlu_kemaskini';

$overallStmt = $conn->prepare("UPDATE audit_forms SET audit_approval_status = ? WHERE id = ? LIMIT 1");
$overallStmt->bind_param('si', $overallStatus, $auditId);
$overallStmt->execute();

$statusLabel = $approvalStatus === 'lulus_diaudit' ? 'Selesai Audit' : 'Perlu Kemaskini';
add_current_user_log($conn, 'Mengubah kelulusan audit ' . $assignedUnit . ' kepada ' . $statusLabel);

header('Location: dashboard.php');
exit();
