<?php
/**
 * Report Cybercrime Form Handler - DATABASE VERSION
 * Handles secure incident report submissions with MySQL storage
 */

// Include database configuration
require_once '../config/db_config.php';

header('Content-Type: application/json');

// Prevent direct access
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Initialize response array
$response = [
    'success' => false,
    'message' => '',
    'errors' => [],
    'referenceId' => ''
];

try {
    // Get database connection
    $pdo = getDBConnection();
    if (!$pdo) {
        throw new Exception('Database connection failed. Please try again later.');
    }

    // =================== COLLECT FORM DATA ===================
    $fullName = isset($_POST['fullName']) ? trim($_POST['fullName']) : '';
    $organization = isset($_POST['organization']) ? trim($_POST['organization']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $position = isset($_POST['position']) ? trim($_POST['position']) : '';
    $contactMethod = isset($_POST['contactMethod']) ? trim($_POST['contactMethod']) : 'Email';
    
    $incidentType = isset($_POST['incidentType']) ? trim($_POST['incidentType']) : '';
    $incidentDate = isset($_POST['incidentDate']) ? trim($_POST['incidentDate']) : '';
    $incidentStatus = isset($_POST['incidentStatus']) ? trim($_POST['incidentStatus']) : 'Ongoing';
    $affectedSystems = isset($_POST['affectedSystems']) ? intval($_POST['affectedSystems']) : 0;
    $incidentDescription = isset($_POST['incidentDescription']) ? trim($_POST['incidentDescription']) : '';
    $priority = isset($_POST['priority']) ? trim($_POST['priority']) : '';
    
    $dataCompromised = isset($_POST['dataCompromised']) ? trim($_POST['dataCompromised']) : 'Unknown';
    $financialImpact = isset($_POST['financialImpact']) ? trim($_POST['financialImpact']) : 'Unknown';
    $businessImpact = isset($_POST['businessImpact']) && is_array($_POST['businessImpact']) 
        ? implode(', ', $_POST['businessImpact']) 
        : '';
    
    $lawEnforcementReported = isset($_POST['lawEnforcement']) ? trim($_POST['lawEnforcement']) : 'Not Yet';
    $lawEnforcementConsent = isset($_POST['consent']) ? 1 : 0;

    // =================== VALIDATION ===================
    if (empty($fullName)) {
        $response['errors']['fullName'] = 'Full name is required';
    }
    if (empty($organization)) {
        $response['errors']['organization'] = 'Organization is required';
    }
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response['errors']['email'] = 'Valid email address is required';
    }
    if (empty($phone)) {
        $response['errors']['phone'] = 'Phone number is required';
    }
    if (empty($incidentType)) {
        $response['errors']['incidentType'] = 'Incident type is required';
    }
    if (empty($incidentDate)) {
        $response['errors']['incidentDate'] = 'Incident date is required';
    }
    if (empty($incidentDescription)) {
        $response['errors']['incidentDescription'] = 'Incident description is required';
    }
    if (empty($priority) || !in_array($priority, ['critical', 'high', 'standard'])) {
        $response['errors']['priority'] = 'Priority level is required';
    }

    // Check if there are validation errors
    if (!empty($response['errors'])) {
        http_response_code(400);
        $response['message'] = 'Please fix the errors below';
        echo json_encode($response);
        exit;
    }

    // =================== GENERATE REFERENCE ID ===================
    $referenceId = 'BCI-' . date('YmdHis') . '-' . strtoupper(substr(md5(uniqid()), 0, 6));

    // =================== FILE UPLOAD HANDLING ===================
    $uploadedFiles = [];
    $maxFileSize = 50 * 1024 * 1024; // 50MB
    $uploadDir = __DIR__ . '/../uploads/incidents/';
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf', 'text/plain', 'application/zip', 'application/x-zip-compressed'];
    $fileUploadErrors = [];

    // Create upload directory if it doesn't exist
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            $fileUploadErrors[] = 'Failed to create upload directory';
        }
    }

    // Handle file uploads
    if (isset($_FILES['evidenceFiles']) && !empty($_FILES['evidenceFiles']['name'][0])) {
        $files = $_FILES['evidenceFiles'];
        
        if (is_array($files['name'])) {
            $fileCount = count($files['name']);

            for ($i = 0; $i < $fileCount; $i++) {
                // Skip empty file slots
                if (empty($files['name'][$i])) {
                    continue;
                }

                // Check for upload errors
                if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                    $errorMsg = '';
                    switch ($files['error'][$i]) {
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            $errorMsg = "File '{$files['name'][$i]}' exceeds maximum upload size";
                            break;
                        case UPLOAD_ERR_PARTIAL:
                            $errorMsg = "File '{$files['name'][$i]}' was only partially uploaded";
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            continue 2; // Skip this file
                            break;
                        case UPLOAD_ERR_NO_TMP_DIR:
                        case UPLOAD_ERR_CANT_WRITE:
                        case UPLOAD_ERR_EXTENSION:
                            $errorMsg = "Server error uploading '{$files['name'][$i]}'";
                            break;
                    }
                    if ($errorMsg) {
                        $fileUploadErrors[] = $errorMsg;
                    }
                    continue;
                }

                $fileName = basename($files['name'][$i]);
                $fileSize = $files['size'][$i];
                $fileTmp = $files['tmp_name'][$i];
                $fileMimeType = mime_content_type($fileTmp);

                // Validate file size
                if ($fileSize > $maxFileSize) {
                    $fileUploadErrors[] = "File '$fileName' exceeds maximum size of 50MB";
                    continue;
                }

                // Validate file type
                if (!in_array($fileMimeType, $allowedTypes)) {
                    $fileUploadErrors[] = "File type '$fileMimeType' not allowed for '$fileName'";
                    continue;
                }

                // Generate unique filename
                $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
                $uniqueFileName = 'evidence_' . uniqid() . '_' . time() . '.' . $fileExtension;
                $uploadPath = $uploadDir . $uniqueFileName;

                // Move uploaded file
                if (move_uploaded_file($fileTmp, $uploadPath)) {
                    $uploadedFiles[] = [
                        'originalName' => $fileName,
                        'storedName' => $uniqueFileName,
                        'size' => $fileSize,
                        'mimeType' => $fileMimeType,
                        'filePath' => $uploadPath
                    ];
                } else {
                    $fileUploadErrors[] = "Failed to save file '$fileName'. Please try again.";
                }
            }
        }
    }

    // =================== INSERT INTO DATABASE ===================
    $pdo->beginTransaction();

    try {
        // Insert main incident report
        $sql = "INSERT INTO incident_reports (
            reference_id, submission_date,
            reporter_full_name, reporter_organization, reporter_email, reporter_phone, 
            reporter_position, reporter_contact_method,
            incident_type, incident_date, incident_status, affected_systems, 
            incident_description, priority,
            data_compromised, financial_impact, business_impact,
            law_enforcement_reported, law_enforcement_consent,
            status
        ) VALUES (
            :reference_id, NOW(),
            :reporter_full_name, :reporter_organization, :reporter_email, :reporter_phone,
            :reporter_position, :reporter_contact_method,
            :incident_type, :incident_date, :incident_status, :affected_systems,
            :incident_description, :priority,
            :data_compromised, :financial_impact, :business_impact,
            :law_enforcement_reported, :law_enforcement_consent,
            'new'
        )";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':reference_id' => $referenceId,
            ':reporter_full_name' => $fullName,
            ':reporter_organization' => $organization,
            ':reporter_email' => $email,
            ':reporter_phone' => $phone,
            ':reporter_position' => $position,
            ':reporter_contact_method' => $contactMethod,
            ':incident_type' => $incidentType,
            ':incident_date' => $incidentDate,
            ':incident_status' => $incidentStatus,
            ':affected_systems' => $affectedSystems,
            ':incident_description' => $incidentDescription,
            ':priority' => $priority,
            ':data_compromised' => $dataCompromised,
            ':financial_impact' => $financialImpact,
            ':business_impact' => $businessImpact,
            ':law_enforcement_reported' => $lawEnforcementReported,
            ':law_enforcement_consent' => $lawEnforcementConsent
        ]);

        $incidentId = $pdo->lastInsertId();

        // Insert uploaded files
        if (!empty($uploadedFiles)) {
            $fileSql = "INSERT INTO evidence_files (
                incident_id, original_filename, stored_filename, file_size, mime_type, file_path, hash_sha256, uploaded_at
            ) VALUES (
                :incident_id, :original_filename, :stored_filename, :file_size, :mime_type, :file_path, :hash_sha256, NOW()
            )";
            
            $fileStmt = $pdo->prepare($fileSql);
            
            foreach ($uploadedFiles as $file) {
                $sha256Hash = hash_file('sha256', $file['filePath']);
                $fileStmt->execute([
                    ':incident_id' => $incidentId,
                    ':original_filename' => $file['originalName'],
                    ':stored_filename' => $file['storedName'],
                    ':file_size' => $file['size'],
                    ':mime_type' => $file['mimeType'],
                    ':file_path' => '/uploads/incidents/' . $file['storedName'],
                    ':hash_sha256' => $sha256Hash
                ]);
            }
        }

        // Log activity
        $logSql = "INSERT INTO incident_activities (incident_id, activity_type, activity_description) 
                   VALUES (:incident_id, 'report_submitted', 'Initial incident report submitted')";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([':incident_id' => $incidentId]);

        // Commit transaction
        $pdo->commit();

        // =================== SEND CONFIRMATION EMAIL ===================
        $to = $email;
        $subject = "BCI Incident Report Received - Reference: $referenceId";
        $headers = "From: noreply@bci.gov\r\n";
        $headers .= "Reply-To: incidents@bci.gov\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

        $emailBody = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #dc3545; color: white; padding: 20px; text-align: center; }
                .content { background-color: #f9f9f9; padding: 20px; }
                .reference { background-color: #e9ecef; padding: 15px; margin: 20px 0; border-left: 4px solid #ffa200; }
                .footer { background-color: #131b30; color: white; padding: 20px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Incident Report Received</h1>
                </div>
                <div class='content'>
                    <p>Dear $fullName,</p>
                    <p>Thank you for reporting a cybercrime incident to the Bureau of Cybercrime Intelligence (BCI).</p>
                    
                    <div class='reference'>
                        <strong>Reference ID:</strong> $referenceId<br>
                        <strong>Priority Level:</strong> " . ucfirst($priority) . "
                    </div>

                    <h3>What Happens Next?</h3>
                    <ul>
                        <li><strong>Critical:</strong> Response within 1 hour</li>
                        <li><strong>High Priority:</strong> Response within 4 hours</li>
                        <li><strong>Standard:</strong> Response within 24 hours</li>
                    </ul>

                    <p><strong>Important:</strong> For emergencies, call our 24/7 hotline at +231 (90) 909 4712.</p>

                    <p>Best regards,<br>Bureau of Cybercrime Intelligence</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2026 Bureau of Cybercrime Intelligence. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";

        // Uncomment to send email in production
        // mail($to, $subject, $emailBody, $headers);

        // =================== SUCCESS RESPONSE ===================
        $response['success'] = true;
        $response['message'] = 'Your incident report has been submitted successfully!';
        $response['referenceId'] = $referenceId;
        $response['uploadedFiles'] = count($uploadedFiles);
        $response['uploadErrors'] = $fileUploadErrors;
        
        http_response_code(200);

    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }

} catch (Exception $e) {
    http_response_code(500);
    $response['success'] = false;
    $response['message'] = 'An error occurred while processing your report. Please try again.';
    error_log("Incident Report Error: " . $e->getMessage());
}

echo json_encode($response);
exit;
?>