<?php

session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../config/koneksi.php';

if(!isset($_SESSION['role'])){
    header("Location: ../index.php");
    exit;
}

if($_SESSION['role'] != 'cs'){
    header("Location: ../index.php");
    exit;
}

$user_id = $_SESSION['id'];

$cs_query = mysqli_query(
    $conn,
    "SELECT * FROM cs_rumah_ibadah
    WHERE user_id='$user_id'"
);

if(!$cs_query){
    die(mysqli_error($conn));
}

$cs = mysqli_fetch_assoc($cs_query);

if(!$cs){
    die("Data CS tidak ditemukan");
}

$cs_id = $cs['id'];

if(!isset($_POST['id'])){
    die("ID bantuan tidak ditemukan");
}

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

if(
    !isset($_FILES['foto']) ||
    $_FILES['foto']['error'] != 0
){
    die("Silakan pilih foto");
}

$tmp = $_FILES['foto']['tmp_name'];
$nama_asli = $_FILES['foto']['name'];

$ext = strtolower(
    pathinfo(
        $nama_asli,
        PATHINFO_EXTENSION
    )
);

$allowed = [
    'jpg',
    'jpeg',
    'png',
    'webp'
];

if(!in_array($ext,$allowed)){
    die("Format file tidak didukung");
}

if(getimagesize($tmp) === false){
    die("File harus berupa gambar");
}

$foto =
    time() . '_' .
    preg_replace(
        '/[^a-zA-Z0-9._-]/',
        '',
        basename($nama_asli)
    );

$cek_query = mysqli_query(
    $conn,
    "SELECT *
    FROM bantuan
    WHERE id='$id'
    AND cs_id='$cs_id'"
);

if(!$cek_query){
    die(mysqli_error($conn));
}

$cek = mysqli_fetch_assoc($cek_query);

if(!$cek){
    die("Akses ditolak");
}

if(!is_dir("../assets/uploads")){
    mkdir("../assets/uploads",0777,true);
}

if(
    !move_uploaded_file(
        $tmp,
        "../assets/uploads/".$foto
    )
){
    die("Upload foto gagal");
}

$update = mysqli_query(
    $conn,
    "UPDATE bantuan
    SET
        bukti_foto='$foto',
        status='selesai'
    WHERE id='$id'"
);

if(!$update){
    die(mysqli_error($conn));
}

$data_query = mysqli_query(
    $conn,
    "SELECT laporan_id
    FROM bantuan
    WHERE id='$id'"
);

if(!$data_query){
    die(mysqli_error($conn));
}

$data = mysqli_fetch_assoc($data_query);

if(!$data){
    die("Data bantuan tidak ditemukan");
}

$laporan_id = $data['laporan_id'];

mysqli_query(
    $conn,
    "UPDATE laporan
    SET status='selesai'
    WHERE id='$laporan_id'"
);

header("Location: tugas.php");
exit;
?>