<?php
include "../config/koneksi.php";
include "../middleware/auth.php";
include "../config/komplain_workflow.php";

sikompro_require_role('pelaksana');

$id = (int) $_POST['id'];

// pilih teknisi (kalau multi teknisi)
$teknisi_id = (int) $_POST['teknisi_id'];
$ket = isset($_POST['keterangan']) ? komplain_escape($conn, $_POST['keterangan']) : '';
$pelaksanaId = (int) $_SESSION['user_id'];
$uploadedBefore = komplain_upload_multiple_images('foto_before', '../uploads/before/', 'before_' . $id);
$existingRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT foto_before FROM komplain WHERE id='$id' AND pelaksana_id='$pelaksanaId' LIMIT 1"));
$fotoBefore = komplain_escape($conn, komplain_merge_images($existingRow['foto_before'] ?? '', $uploadedBefore));

mysqli_query($conn,"
    UPDATE komplain 
    SET 
        status='dikirim_ke_teknisi',
        teknisi_id='$teknisi_id',
        pelaksana_id='$pelaksanaId',
        pelaksana_keterangan='$ket',
        catatan_pelaksana=NULL,
        foto_before=CASE
            WHEN '$fotoBefore' <> '' THEN '$fotoBefore'
            ELSE foto_before
        END,
        tanggal_update=NOW()
    WHERE id='$id'
      AND pelaksana_id='$pelaksanaId'
");

header("Location: dashboard.php");
