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

$servername = "localhost";
$username = "myprojec_allytec";
$password = "allytech@2019";
$dbname = "myprojec_patient";

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

// Check connection
if ($conn->connect_error) {
    die(json_encode(['status' => 'error', 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

// Ensure the request is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the form data
    $username = $conn->real_escape_string($_POST['username']);
    $type_of_donation = $conn->real_escape_string($_POST['type_of_donation']);
    $ddate = $conn->real_escape_string($_POST['ddate']);
    $description = $conn->real_escape_string($_POST['description']);
    $trust_name = $conn->real_escape_string($_POST['trust_name']);
    $trust_address = $conn->real_escape_string($_POST['trust_address']);
    $name = $conn->real_escape_string($_POST['name']);
    $randomno = $conn->real_escape_string($_POST['randomno']);
    
    $address = $conn->real_escape_string($_POST['address']);
    $contactno = $conn->real_escape_string($_POST['contactno']);
    $whatsappno = $conn->real_escape_string($_POST['whatsappno']);
    $aadhar= $conn->real_escape_string($_POST['aadhar']);
    $occation= $conn->real_escape_string($_POST['occation']);
    $amount= $conn->real_escape_string($_POST['amount']);

    // 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'];

        // Validate file type and size
        $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(['status' => 'error', 'message' => 'Invalid file type. Only JPG, JPEG, PNG files are allowed.']);
            exit;
        }

        if ($file_size > 2 * 1024 * 1024) {
            echo json_encode(['status' => 'error', 'message' => 'File size exceeds the 2MB limit.']);
            exit;
        }

        // Define the upload directory
        $upload_dir = "uploads/";
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $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
            $sql = "INSERT INTO donation_tbl (username, type_of_donation, ddate, description, trust_name, trust_address, filename,name,random_no,address,contactno,whatsappno,amount) 
                    VALUES ('$username', '$type_of_donation', '$ddate', '$description', '$trust_name', '$trust_address', '$file_path','$name','$randomno','$address','$contactno','$whatsappno','$amount')";

            if ($conn->query($sql) === TRUE) {
                // Send the confirmation email
                $subject = "Donation Confirmation";
                $message = "
                    <html>
                    <head>
                        <title>Donation Confirmation</title>
                    </head>
                    <body>
                        <p>Dear $username-$randomno,</p>
                        <p>Thank you for your donation. Your donation has been successfully recorded.</p>
                        <p>Details:</p>
                        <ul>
                            <li>Type of Donation: $type_of_donation</li>
                            <li>Date: $ddate</li>
                            <li>Description:$occation - $description</li>
                            <li>Trust Name: $trust_name</li>
                            <li>Trust Address: $trust_address</li>
                        </ul>
                        <p>Best regards,</p>
                        <p>Your Team</p>
                    </body>
                    </html>
                ";
                
                $messagenew = "
    <html>
    <head>
        <title>Food Sponsorship - Donation Confirmation</title>
    </head>
    <body>
        <p>Dear Donor,</p>
        <p>Thank you for your generous donation! Below are the details:</p>
        <ul>
            <li><strong>Purpose:</strong> Food sponsorship  at $trust_name on $ddate</li>
            <li><strong>Donor:</strong>$username</li>
           
            <li><strong>Address:</strong> $address</li>
            <li><strong>Mobile:</strong> $contactno</li>
            
            <li><strong>Aadhar:</strong>$aadhar</li>
            <li><strong>Occasion:</strong>$occation-  $description</li>
            <li><strong>Donation Amount:</strong> Rs.$amount /- Paid</li>
            <li><strong>Reference:</strong> RM - DR</li>
        </ul>
        <p>We truly appreciate your support in making a difference!</p>
        <p>Best regards,</p>
        <p>Your Organization Team</p>
    </body>
    </html>
";

                // Email headers
                $headers = "From: no-reply@myprojectfinal.in\r\n";
                $headers .= "Reply-To: no-reply@myprojectfinal.in\r\n";
                $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

                if (mail($name, $subject, $messagenew, $headers)) {
                    echo json_encode(['status' => 'success', 'message' => 'Donation inserted successfully. Email sent.']);
                } else {
                    echo json_encode(['status' => 'warning', 'message' => 'Donation inserted, but email sending failed.']);
                }
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Database insertion failed: ' . $conn->error]);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to upload image.']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No image uploaded or there was an error with the file.']);
    }
    $conn->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
