<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_log("=== Submit Report Called ===", 3, "/tmp/construction_reports.log");

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Database connection
require_once 'db_config.php';

// Start session to get engineer info
session_start();

try {
    // Validate required fields
    $required_fields = ['report_date', 'shift', 'activity_id', 'quantity_completed', 
                       'progress_percentage', 'cumulative_percentage'];
    
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || $_POST[$field] === '') {
            throw new Exception("Missing required field: $field");
        }
    }

    // Get engineer and project info from session
    $engineer_id = $_SESSION['engineer_id'] ?? 1; // Default for testing
    $project_id = $_SESSION['project_id'] ?? 1;   // Default for testing

    // Start transaction
    $conn->begin_transaction();

    // Get WBS ID from activity_id and project_id
    $stmt = $conn->prepare("SELECT wbs_id FROM project_wbs WHERE project_id = ? AND activity_id = ? LIMIT 1");
    $stmt->bind_param('ii', $project_id, intval($_POST['activity_id']));
    $stmt->execute();
    $result = $stmt->get_result();
    $wbs_row = $result->fetch_assoc();
    
    if (!$wbs_row) {
        throw new Exception('Activity not found in project WBS');
    }
    
    $wbs_id = $wbs_row['wbs_id'];

    // Insert daily report
    $insert_sql = "INSERT INTO daily_reports (
        project_id, wbs_id, engineer_id, report_date, shift,
        quantity_completed, progress_percentage, cumulative_percentage,
        manpower_count, equipment_used, remarks, weather_condition,
        delay_reason, safety_incidents, quality_issues, status, submitted_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param('iiissdddisssiis',
        $project_id,
        $wbs_id,
        $engineer_id,
        $_POST['report_date'],
        $_POST['shift'],
        floatval($_POST['quantity_completed']),
        floatval($_POST['progress_percentage']),
        floatval($_POST['cumulative_percentage']),
        intval($_POST['manpower_count'] ?? 0),
        $_POST['equipment_used'] ?? '',
        $_POST['remarks'] ?? '',
        $_POST['weather_condition'] ?? '',
        $_POST['delay_reason'] ?? '',
        intval($_POST['safety_incidents'] ?? 0),
        intval($_POST['quality_issues'] ?? 0),
        $_POST['status'] ?? 'Submitted'
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to insert daily report: ' . $stmt->error);
    }
    
    $report_id = $conn->insert_id;

    // Handle photo uploads
    $photo_count = 0;
    $upload_dir = '../uploads/reports/' . date('Y/m/d') . '/';
    
    // Create directory if it doesn't exist
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Process each uploaded photo
    foreach ($_FILES as $key => $file) {
        if (strpos($key, 'photo_') === 0 && $file['error'] === UPLOAD_ERR_OK) {
            $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array($file_extension, $allowed_extensions)) {
                continue;
            }

            // Generate unique filename
            $new_filename = 'report_' . $report_id . '_' . uniqid() . '.' . $file_extension;
            $file_path = $upload_dir . $new_filename;
            
            if (move_uploaded_file($file['tmp_name'], $file_path)) {
                // Get GPS coordinates if provided
                $photo_index = str_replace('photo_', '', $key);
                $gps_lat = isset($_POST["photo_{$photo_index}_lat"]) ? floatval($_POST["photo_{$photo_index}_lat"]) : null;
                $gps_lng = isset($_POST["photo_{$photo_index}_lng"]) ? floatval($_POST["photo_{$photo_index}_lng"]) : null;
                
                // Insert photo record
                $photo_sql = "INSERT INTO report_photos (
                    report_id, photo_filename, photo_path, photo_caption,
                    gps_latitude, gps_longitude, file_size_kb
                ) VALUES (?, ?, ?, ?, ?, ?, ?)";
                
                $photo_stmt = $conn->prepare($photo_sql);
                $file_size_kb = round(filesize($file_path) / 1024, 2);
                $caption = "Progress photo " . ($photo_count + 1);
                
                $photo_stmt->bind_param('isssddd',
                    $report_id,
                    $new_filename,
                    $file_path,
                    $caption,
                    $gps_lat,
                    $gps_lng,
                    $file_size_kb
                );
                
                if ($photo_stmt->execute()) {
                    $photo_count++;
                }
            }
        }
    }

    // Update activity progress
    $update_progress_sql = "INSERT INTO activity_progress (
        wbs_id, as_of_date, cumulative_quantity, cumulative_percentage
    ) VALUES (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        cumulative_quantity = VALUES(cumulative_quantity),
        cumulative_percentage = VALUES(cumulative_percentage)";
    
    $cumulative_quantity = floatval($_POST['quantity_completed']); // Should be cumulative from previous reports
    $stmt = $conn->prepare($update_progress_sql);
    $stmt->bind_param('isdd',
        $wbs_id,
        $_POST['report_date'],
        $cumulative_quantity,
        floatval($_POST['cumulative_percentage'])
    );
    $stmt->execute();

    // Commit transaction
    $conn->commit();

    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Report submitted successfully',
        'report_id' => $report_id,
        'photos_uploaded' => $photo_count
    ]);

} catch (Exception $e) {
    // Rollback on error
    if (isset($conn)) {
        $conn->rollback();
    }
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

if (isset($conn)) {
    $conn->close();
}
?>