<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $kj = $_POST['kj'];
    $division = $_POST['division'];
    $block = $_POST['block'];
    $damageType = $_POST['damageType'];
    $classification = $_POST['classification'];
    $mitigationPlan = $_POST['mitigationPlan'];
    $notes = $_POST['notes'];
    $waktu_temuan = $_POST['waktu_temuan']; // New field

    // Debug: Check if waktu_temuan is received
    error_log("Waktu temuan received: " . $waktu_temuan);

    // Generate unique ID
    $lastIdQuery = "SELECT MAX(CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(id, '-', -1), '-', -1) AS UNSIGNED)) as lastId FROM Report WHERE id LIKE 'ID-" . $kj . "%';";
    $lastIdResult = $conn->query($lastIdQuery);

    if ($lastIdResult) {
        $lastIdRow = $lastIdResult->fetch_assoc();
        $lastId = $lastIdRow['lastId'];
        $newIdNumber = $lastId ? intval($lastId) + 1 : 1;
    } else {
        $newIdNumber = 1;
    }

    $id = "ID-" . $kj . "-" . $newIdNumber;

    // Handle file upload
    $initialPhoto = $_FILES['initialPhoto'];
    if ($initialPhoto['error'] === UPLOAD_ERR_OK) {
        $initialPhotoPath = 'uploads/' . $id . "-" . basename($initialPhoto['name']);
        move_uploaded_file($initialPhoto['tmp_name'], $initialPhotoPath);
    } else {
        $initialPhotoPath = null;
    }
    
    // Set timezone and current timestamp for system tracking
    date_default_timezone_set('Asia/Jakarta');
    $timestamp = date("Y-m-d H:i:s");
    $status = 'Belum Ditangani';

    // Check if columns exist before inserting
    $checkColumns = "SHOW COLUMNS FROM Report LIKE 'waktu_temuan'";
    $result = $conn->query($checkColumns);
    
    if ($result->num_rows == 0) {
        // Column doesn't exist, add it
        $addColumn = "ALTER TABLE Report ADD COLUMN waktu_temuan DATETIME NULL AFTER timestamp";
        $conn->query($addColumn);
    }

    // Prepare statement with correct column names
    $stmt = $conn->prepare("INSERT INTO Report (id, timestamp, waktu_temuan, division, block, kj, damageType, classification, mitigationPlan, notes, initialPhoto, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }
    
    $stmt->bind_param("ssssssssssss", $id, $timestamp, $waktu_temuan, $division, $block, $kj, $damageType, $classification, $mitigationPlan, $notes, $initialPhotoPath, $status);

    if ($stmt->execute()) {
        echo "<script>alert('Data berhasil disimpan!'); window.location.href='/?active=kerusakan';</script>";
    } else {
        echo "Error: " . $stmt->error;
        error_log("Database error: " . $stmt->error);
    }

    $stmt->close();
    $conn->close();
}
?>
