<?php
include 'config.php';

// Check if we received the form via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $user_id = isset($_GET['user']) ? $_GET['user'] : 'testuser';
    $amount = isset($_POST['amount_due']) ? $_POST['amount_due'] : 0;
    $company_id = isset($_POST['company_id']) ? $_POST['company_id'] : null;
    
    // We are now receiving the image as a text string (Base64)
    $image_data = isset($_POST['image_data']) ? $_POST['image_data'] : '';

    $target_file = "";

    // 1. Convert the text string back into a physical image file
    if (!empty($image_data)) {
        $target_dir = "uploads/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0755, true);
        }

        // Strip the header from the Base64 string
        // (e.g., "data:image/jpeg;base64,xxxx")
        $img_parts = explode(";base64,", $image_data);
        if (count($img_parts) == 2) {
            $image_base64 = base64_decode($img_parts[1]);
            $filename = $user_id . "_" . time() . ".jpg";
            $target_file = $target_dir . $filename;
            
            // Save the file to the folder
            file_put_contents($target_file, $image_base64);
        }
    }

    // 2. Save the details to the Database
    try {
        $sql = "INSERT INTO invoices (user_id, company_id, amount_due, image_path, is_paid, date_received) 
                VALUES (:uid, :cid, :amt, :img, 0, NOW())";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':uid' => $user_id,
            ':cid' => $company_id,
            ':amt' => $amount,
            ':img' => $target_file
        ]);

        // Success - Go back to dashboard
        header("Location: index.php?user=" . $user_id);
        exit;

    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
        exit;
    }

} else {
    echo "No data submitted.";
}
?>