<?php
// insert_donation.php
header("Content-Type: application/json");

$servername = "localhost";
$username = "myprojec_allytec";
$password = "allytech@2019";
$dbname = "myprojec_patient";  // Replace with your actual database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Ensure the request is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the other form data
    $username = $_POST['username'];
    $type_of_donation = $_POST['type_of_donation'];
    $ddate = $_POST['ddate'];
    $description = $_POST['description'];
    $trust_name = $_POST['trust_name'];
    $trust_address = $_POST['trust_address'];

    // Handle the image upload
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $file_tmp_name = $_FILES['image']['tmp_name'];
        $file_name = $_FILES['image']['name'];
        $file_size = $_FILES['image']['size'];
        $file_error = $_FILES['image']['error'];

        // Check if the file is valid (e.g., check the file size and type)
        $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
        $file_type = mime_content_type($file_tmp_name);

        if (!in_array($file_type, $allowed_types)) {
            echo json_encode(['message' => 'Invalid file type. Only JPG, JPEG, PNG files are allowed.']);
            exit;
        }

        // Check file size (e.g., limit to 2MB)
        if ($file_size > 2 * 1024 * 1024) {
            echo json_encode(['message' => 'File size exceeds the limit. Max size is 2MB.']);
            exit;
        }

        // Define the upload directory and file path
        $upload_dir = "uploads/";
        $file_path = $upload_dir . basename($file_name);

        // Move the uploaded file to the target directory
        if (move_uploaded_file($file_tmp_name, $file_path)) {
            // Insert the donation data into the database, including the file path
            $sql = "INSERT INTO donation_tbl (username, type_of_donation, ddate, description, trust_name, trust_address, filename) 
                    VALUES ('$username', '$type_of_donation', '$ddate', '$description', '$trust_name', '$trust_address', '$file_path')";

            if ($conn->query($sql) === TRUE) {
                sendEmailNotification($username);
                 echo json_encode(['status' => 'success', 'message' => 'Donation inserted successfully. Email sent.']);
            } else {
                 echo json_encode(['status' => 'error', 'message' => $conn->error]);
            }
        } else {
            echo json_encode(['message' => 'Failed to upload image.']);
        }
    } else {
        echo json_encode(['message' => 'No image uploaded or there was an error with the file.']);
    }
    $conn->close();
}

// Function to send an email to the logged-in user
function sendEmailNotification($username) {
    // Fetch the user's email based on the username
$ma = $username;
$mas ="Dear $username,\n\nThank you for your donation. Your donation has been successfully recorded.\n\nBest regards,\nYour Team";

// Recipient 
$to = $ma;
$from = 'maniram8694@myprojectfinal.in';
$fromName = 'test';

// Email subject 
$subject = "Donation Confirmation";
$message = "Dear $username,\n\nThank you for your donation. Your donation has been successfully recorded.\n\nBest regards,\nYour Team";

// Email body content 
$htmlContent = '<h3>' . $message . '</h3>';

// Header for sender info 
$headers = "From: $fromName" . " <" . $from . ">";

// Boundary  
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Headers for attachment  
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

// Multipart boundary  
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";

$mail = mail($to, $subject, $mas, $headers);

if ($mail) {
   echo "Mail Sent";
} else {
    // Get the last error
    $error = error_get_last();
    echo "Error sending email: " . $error['message'];
}
 
   
}


?>
