<?php

// error_reporting(0);

// Check if the form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Connect to the database



$conn = mysqli_connect('localhost', 'sarmotorismo_formenter', 'D6l!DHytJFZ2', 'sarmotorismo_formenter');



// $conn = mysqli_connect('localhost', 'root', '', 'event');

if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

}



    //Event data fia

    $ti_check = isset($_POST['ti_check']) ? "Yes" : "NO";

    $select_class = $_POST['select_class'];

    $t2_check = isset($_POST['t2_check']) ? "Yes" : "NO";

    $t3_check = isset($_POST['t3_check']) ? "Yes" : "NO";

    $sec_class = $_POST['sec_class'];

    $t4_check = isset($_POST['t4_check']) ? "Yes" : "No";





    //National data

    $grupo_t1_nac = isset($_POST['grupo_t1_nac']) ? "Yes" : "No";

    $classe_t1_nac = $_POST['classe_t1_nac'];

    $grupo_t2_nac = isset($_POST['grupo_t2_nac']) ? "Yes" : "No";

    $grupo_t3_nac = isset($_POST['grupo_t3_nac']) ? "Yes" : "No";

    $grupo_t4_nac = isset($_POST['grupo_t4_nac']) ? "Yes" : "No";

    $class_t4_nac = $_POST['class_t4_nac'];

    $grupo_t8_nac = isset($_POST['grupo_t8_nac']) ? "Yes" : "No";

    $grupo_t9_nac = isset($_POST['grupo_t9_nac']) ? "Yes" : "No";



    //COMPETITOR 

    $comp_name = $_POST['comp_name'];

    $comp_licen = $_POST['comp_licen'];

    $team_manag = $_POST['team_manag'];

    $comp_mobile = $_POST['comp_mobile'];

    $comp_mail = $_POST['comp_mail'];



    //FIRST DRIVER / PILOTO

    $driver_surname = $_POST['driver_surname'];

    $driver_fname = $_POST['driver_fname'];

    $driv_nationality = $_POST['driv_nationality'];

    $driv_adress = $_POST['driv_adress'];

    $driv_passport = $_POST['driv_passport'];

    $driv_mobile = $_POST['driv_mobile'];

    $driv_mail = $_POST['driv_mail'];

    $driv_compit_lice = $_POST['driv_compit_lice'];

    $driv_issu_asn = $_POST['driv_issu_asn'];

    $driving_lice = $_POST['driving_lice'];

    $count_of_issue = $_POST['count_of_issue'];



    //SECOND DRIVER /CO-PILOTO

    $sec_driv_surname = $_POST['sec_driv_surname'];

    $sec_driv_fname = $_POST['sec_driv_fname'];

    $sec_driv_nationality_co = $_POST['sec_driv_nationality_co'];

    $sec_driv_adress = $_POST['sec_driv_adress'];

    $sec_driv_passport_co = $_POST['sec_driv_passport_co'];

    $sec_driv_mobile_co = $_POST['sec_driv_mobile_co'];

    $sec_driv_email_co = $_POST['sec_driv_email_co'];

    $sec_driv_competitionLicense_co = $_POST['sec_driv_competitionLicense_co'];

    $sec_driv_issuingASN_co = $_POST['sec_driv_issuingASN_co'];

    $sec_driv_drivingLicense_co = $_POST['sec_driv_drivingLicense_co'];

    $sec_driv_countryOfIssue_co = $_POST['sec_driv_countryOfIssue_co'];



    //EMERGENCY CONTACT

    $emergency_surname = $_POST['emergency_surname'];

    $emergency_fname = $_POST['emergency_fname'];

    $emergency_mobile = $_POST['emergency_mobile'];

    $emergency_mail = $_POST['emergency_mail'];



    //COMPETITION VEHICLE/VEÍCULO

    $comp_vehicle_make = $_POST['comp_vehicle_make'];

    $comp_vehicle_model = $_POST['comp_vehicle_model'];

    $comp_vehicle_registrationNo = $_POST['comp_vehicle_registrationNo'];

    $comp_vehicle_cc = $_POST['comp_vehicle_cc'];

    $comp_vehicle_chassisNo = $_POST['comp_vehicle_chassisNo'];

    $comp_vehicle_technicalPassportNo = $_POST['comp_vehicle_technicalPassportNo'];

    $comp_vehicle_yearOfManufacture = $_POST['comp_vehicle_yearOfManufacture'];

    $comp_vehicle_group = $_POST['comp_vehicle_group'];

    $comp_vehicle_homologationNo = $_POST['comp_vehicle_homologationNo'];

    $comp_vehicle_countryOfRegistration = $_POST['comp_vehicle_countryOfRegistration'];

    

    

    //invoice 

    $invoicename = $_POST['invoicename'];

    $invoiceaddress = $_POST['invoiceaddress'];

    $invoiceid = $_POST['invoiceid'];



    //register

    $shakedown_check = isset($_POST['shakedown_check']) ? 1 : 0;



    //agree

    $agree_check = isset($_POST['agree_check']) ? 1 : 0;



    $insert_event = "INSERT INTO events SET FIA_t1='$ti_check', FIA_class='$select_class', FIA_t2='$t2_check', FIA_t3='$t3_check', sec_class= '$sec_class', FIA_t4='$t4_check', grupo_t1_nac='$grupo_t1_nac', classe_t1_nac='$classe_t1_nac', grupo_t2_nac='$grupo_t2_nac', grupo_t3_nac='$grupo_t3_nac', grupo_t4_nac='$grupo_t4_nac', class_t4_nac='$class_t4_nac', grupo_t8_nac='$grupo_t8_nac', grupo_t9_nac='$grupo_t9_nac', comp_name='$comp_name', comp_licen='$comp_licen', team_manag='$team_manag', comp_mobile='$comp_mobile', comp_mail='$comp_mail'

    ";



    $run = $conn->query($insert_event);



    if($run){

       $slct = "SELECT id FROM events Where comp_mail='$comp_mail'";

       $slctRun = $conn->query($slct);

       while($data = mysqli_fetch_assoc($slctRun)){

        $uid = $data['id'];

       }

       

       //insert drivers

       $insert_driv = "INSERT INTO drivers SET comp_id='$uid', driver_surname='$driver_surname', driver_fname='$driver_fname', driv_nationality='$driv_nationality', driv_adress='$driv_adress', driv_passport='$driv_passport', driv_mobile='$driv_mobile', driv_mail='$driv_mail', driv_compit_lice='$driv_compit_lice', driv_issu_asn='$driv_issu_asn', driving_lice='$driving_lice', count_of_issue='$count_of_issue', sec_driv_surname='$sec_driv_surname', sec_driv_fname='$sec_driv_fname', sec_driv_nationality_co='$sec_driv_nationality_co', sec_driv_adress='$sec_driv_adress', sec_driv_passport_co='$sec_driv_passport_co', sec_driv_mobile_co='$sec_driv_mobile_co', sec_driv_email_co='$sec_driv_email_co', sec_driv_competitionLicense_co='$sec_driv_competitionLicense_co', sec_driv_issuingASN_co='$sec_driv_issuingASN_co', sec_driv_drivingLicense_co='$sec_driv_drivingLicense_co', sec_driv_countryOfIssue_co='$sec_driv_countryOfIssue_co'

       ";



       $runDriver = $conn->query($insert_driv);





       $insertContact = "INSERT INTO contacts SET comp_id='$uid',

                                                    emergency_surname='$emergency_surname',

                                                    emergency_fname='$emergency_fname',

                                                    emergency_mobile='$emergency_mobile',

                                                    emergency_mail='$emergency_mail'

                                                     ";

        $contRun=$conn->query($insertContact);

        

        

        $insertVoice = "INSERT INTO invoices SET user_id='$uid', name='$invoicename', invoiceaddress='$invoiceaddress', invoice_id='$invoiceid'";

        $InvoiceRun=$conn->query($insertVoice);





        $insert_vehicle="INSERT INTO vehicle SET comp_id='$uid',

                                                comp_vehicle_make='$comp_vehicle_make',

                                                comp_vehicle_model='$comp_vehicle_model',

                                                comp_vehicle_registrationNo='$comp_vehicle_registrationNo',

                                                comp_vehicle_cc='$comp_vehicle_cc',

                                                comp_vehicle_chassisNo='$comp_vehicle_chassisNo',

                                                comp_vehicle_technicalPassportNo='$comp_vehicle_technicalPassportNo',

                                                comp_vehicle_yearOfManufacture='$comp_vehicle_yearOfManufacture',

                                                comp_vehicle_group='$comp_vehicle_group',

                                                comp_vehicle_homologationNo='$comp_vehicle_homologationNo',

                                                comp_vehicle_countryOfRegistration='$comp_vehicle_countryOfRegistration'    ";



        $runVehcile=$conn->query($insert_vehicle);







        





        if ($runVehcile) {

            // File handling

            function saveUploadedFile($file)

            {

                $targetDirectory = "attachments/";

                $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);

                $uniqueName = uniqid() . "." . $fileExtension;

                $targetFilePath = $targetDirectory . $uniqueName;

                move_uploaded_file($file["tmp_name"], $targetFilePath);

                return $uniqueName;

            }

        

            try {

                // Define the file input names in an array

                $uploadedFiles = array(

                    "firstDriverPassport",

                    "firstDriverLicense",

                    "firstDriverDrivingLicense",

                    "secondDriverPassport",

                    "secondDriverLicense",

                    "secondDriverDrivingLicense",

                    "carDocuments",

                    "technicalPassport",

                    "insurance",

                    "homologationNo_file" // Make sure you have a corresponding input element in the HTML for this

                );

        

                // Prepare the SQL INSERT statement with placeholders using question marks

                $sql = "INSERT INTO attachments (user_id, firstDriverPassport, firstDriverLicense, firstDriverDrivingLicense, secondDriverPassport, secondDriverLicense, secondDriverDrivingLicense, carDocuments, technicalPassport, insurance, homologationNo_file) 

                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        

                // Prepare the statement

                $stmt = $conn->prepare($sql);

        

                // Collect the filenames in an array

                $fileNames = array();

        

                foreach ($uploadedFiles as $fileInputName) {

                    if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {

                        $filename = saveUploadedFile($_FILES[$fileInputName]);

                        $fileNames[] = $filename; // Store the filename for binding later

                    }

                }

        

                // Determine the data types for bind_param

                $dataTypes = str_repeat('s', count($fileNames) + 1);

        

                // Bind parameters for the statement

                $params = array_merge(array($dataTypes, $uid), $fileNames);

                $stmt->bind_param(...$params);

        

                // Execute the SQL statement

                $stmt->execute();

        

                // echo "Files uploaded and saved successfully!";

            } catch (mysqli_sql_exception $e) {

                echo "Error: " . $e->getMessage();

            }

            // E-mail handling



            $admin_email = "info@entries.sar-motorismo.com"; //admin email to send

            $subject = "Event Information - New Submission";



            // Prepare the email content

            // Prepare the email content in table format

            $email_content = "<table border='1' cellpadding='5' cellspacing='0'>";

            $email_content .= "<tr><th colspan='2'>Event Data FIA</th></tr>";

            $email_content .= "<tr><td>FIA_t1</td><td>$ti_check</td></tr>";

            $email_content .= "<tr><td>FIA_class</td><td>$select_class</td></tr>";

            $email_content .= "<tr><td>FIA_t2</td><td>$t2_check</td></tr>";

            $email_content .= "<tr><td>FIA_t3</td><td>$t3_check</td></tr>";

            $email_content .= "<tr><td>sec_class</td><td>$sec_class</td></tr>";

            $email_content .= "<tr><td>FIA_t4</td><td>$t4_check</td></tr>";



            $email_content .= "<tr><th colspan='2'>National Data</th></tr>";

            $email_content .= "<tr><td>grupo_t1_nac</td><td>$grupo_t1_nac</td></tr>";

            $email_content .= "<tr><td>classe_t1_nac</td><td>$classe_t1_nac</td></tr>";

            $email_content .= "<tr><td>grupo_t2_nac</td><td>$grupo_t2_nac</td></tr>";

            $email_content .= "<tr><td>grupo_t3_nac</td><td>$grupo_t3_nac</td></tr>";

            $email_content .= "<tr><td>grupo_t4_nac</td><td>$grupo_t4_nac</td></tr>";

            $email_content .= "<tr><td>class_t4_nac</td><td>$class_t4_nac</td></tr>";

            $email_content .= "<tr><td>grupo_t8_nac</td><td>$grupo_t8_nac</td></tr>";

            $email_content .= "<tr><td>grupo_t9_nac</td><td>$grupo_t9_nac</td></tr>";



            $email_content .= "<tr><th colspan='2'>Competitor Information</th></tr>";

            $email_content .= "<tr><td>Name</td><td>$comp_name</td></tr>";

            $email_content .= "<tr><td>License</td><td>$comp_licen</td></tr>";

            $email_content .= "<tr><td>Team Manager</td><td>$team_manag</td></tr>";

            $email_content .= "<tr><td>Mobile</td><td>$comp_mobile</td></tr>";

            $email_content .= "<tr><td>Email</td><td>$comp_mail</td></tr>";



            $email_content .= "<tr><th colspan='2'>First Driver / Piloto</th></tr>";

            $email_content .= "<tr><td>Surname</td><td>$driver_surname</td></tr>";

            $email_content .= "<tr><td>First Name</td><td>$driver_fname</td></tr>";

            $email_content .= "<tr><td>Nationality</td><td>$driv_nationality</td></tr>";

            $email_content .= "<tr><td>Address</td><td>$driv_adress</td></tr>";

            $email_content .= "<tr><td>Passport</td><td>$driv_passport</td></tr>";

            $email_content .= "<tr><td>Mobile</td><td>$driv_mobile</td></tr>";

            $email_content .= "<tr><td>Email</td><td>$driv_mail</td></tr>";

            $email_content .= "<tr><td>Competition License</td><td>$driv_compit_lice</td></tr>";

            $email_content .= "<tr><td>Issuing ASN</td><td>$driv_issu_asn</td></tr>";

            $email_content .= "<tr><td>Driving License</td><td>$driving_lice</td></tr>";

            $email_content .= "<tr><td>Count of Issue</td><td>$count_of_issue</td></tr>";



            $email_content .= "<tr><th colspan='2'>Second Driver / Co-Piloto</th></tr>";

            $email_content .= "<tr><td>Surname</td><td>$sec_driv_surname</td></tr>";

            $email_content .= "<tr><td>First Name</td><td>$sec_driv_fname</td></tr>";

            $email_content .= "<tr><td>Nationality</td><td>$sec_driv_nationality_co</td></tr>";

            $email_content .= "<tr><td>Address</td><td>$sec_driv_adress</td></tr>";

            $email_content .= "<tr><td>Passport</td><td>$sec_driv_passport_co</td></tr>";

            $email_content .= "<tr><td>Mobile</td><td>$sec_driv_mobile_co</td></tr>";

            $email_content .= "<tr><td>Email</td><td>$sec_driv_email_co</td></tr>";

            $email_content .= "<tr><td>Competition License</td><td>$sec_driv_competitionLicense_co</td></tr>";

            $email_content .= "<tr><td>Issuing ASN</td><td>$sec_driv_issuingASN_co</td></tr>";

            $email_content .= "<tr><td>Driving License</td><td>$sec_driv_drivingLicense_co</td></tr>";

            $email_content .= "<tr><td>Country of Issue</td><td>$sec_driv_countryOfIssue_co</td></tr>";



            $email_content .= "<tr><th colspan='2'>Emergency Contact</th></tr>";

            $email_content .= "<tr><td>Surname</td><td>$emergency_surname</td></tr>";

            $email_content .= "<tr><td>First Name</td><td>$emergency_fname</td></tr>";

            $email_content .= "<tr><td>Mobile</td><td>$emergency_mobile</td></tr>";

            $email_content .= "<tr><td>Email</td><td>$emergency_mail</td></tr>";



            $email_content .= "<tr><th colspan='2'>Competition Vehicle / Veículo</th></tr>";

            $email_content .= "<tr><td>Make</td><td>$comp_vehicle_make</td></tr>";

            $email_content .= "<tr><td>Model</td><td>$comp_vehicle_model</td></tr>";

            $email_content .= "<tr><td>Registration No.</td><td>$comp_vehicle_registrationNo</td></tr>";

            $email_content .= "<tr><td>CC</td><td>$comp_vehicle_cc</td></tr>";

            $email_content .= "<tr><td>Chassis No.</td><td>$comp_vehicle_chassisNo</td></tr>";

            $email_content .= "<tr><td>Technical Passport No.</td><td>$comp_vehicle_technicalPassportNo</td></tr>";

            $email_content .= "<tr><td>Year of Manufacture</td><td>$comp_vehicle_yearOfManufacture</td></tr>";

            $email_content .= "<tr><td>Group</td><td>$comp_vehicle_group</td></tr>";

            $email_content .= "<tr><td>Homologation No.</td><td>$comp_vehicle_homologationNo</td></tr>";

            $email_content .= "<tr><td>Country of Registration</td><td>$comp_vehicle_countryOfRegistration</td></tr>";

            

             $email_content .= "<a href='https://www.sar-motorismo.com/test/excel.php' style='padding: 10px 20px; color: white; background: green;'>Download Excel Records</a>\n";

            

             $email_content .= "<tr><th colspan='2'>Invoice details/Dados de facturação</th></tr>";

            $email_content .= "<tr><td>Name</td><td>$invoicename</td></tr>";

            $email_content .= "<tr><td>Address</td><td>$invoiceaddress</td></tr>";

            $email_content .= "<tr><td>Invoice Id</td><td>$invoiceid</td></tr>";



            $email_content .= "</table>";

           

           $queryslct = "SELECT * FROM attachments WHERE user_id='$uid'";

            $resultquery = mysqli_query($conn, $queryslct);

            if (mysqli_num_rows($resultquery) === 1) {

                while($filedata = mysqli_fetch_assoc($resultquery)){

                    $firstDriverPassport = $filedata['firstDriverPassport'];

                    $firstDriverLicense = $filedata['firstDriverLicense'];

                    $firstDriverDrivingLicense = $filedata['firstDriverDrivingLicense'];

                    $secondDriverPassport = $filedata['secondDriverPassport'];

                    $secondDriverLicense = $filedata['secondDriverLicense'];

                    $secondDriverDrivingLicense = $filedata['secondDriverDrivingLicense'];

                    $carDocuments = $filedata['carDocuments'];

                    $technicalPassport = $filedata['technicalPassport'];

                    $insurance = $filedata['insurance'];

                    $homologationNo_file = $filedata['homologationNo_file'];



                    $file_url_one = "First Driver Passport : <a href='https://www.sar-motorismo.com/test/attachments/$firstDriverLicense'>See Files Here</a> <br/>";

                    

                    $file_url_two = "First Driver License : <a href='https://www.sar-motorismo.com/test/attachments/$firstDriverPassport'>See Files Here</a> <br/>";

                    

                    $file_url_3 = "First Driver Driving License : <a href='https://www.sar-motorismo.com/test/attachments/$firstDriverDrivingLicense'>See Files Here</a> <br/>";

                    

                    $file_url_4 = "Second Driver Passport: <a href='https://www.sar-motorismo.com/test/attachments/$secondDriverPassport'>See Files Here</a> <br/>";

                    

                    $file_url_5 = "Second Driver License: <a href='https://www.sar-motorismo.com/test/attachments/$secondDriverLicense'>See Files Here</a> <br/>";

                    

                    $file_url_6 = "Second Driver Driving License: <a href='https://www.sar-motorismo.com/test/attachments/$secondDriverDrivingLicense'>See Files Here</a> <br/>";

                    

                    $file_url_7 = "Car Documents: <a href='https://www.sar-motorismo.com/test/attachments/$carDocuments'>See Files Here</a> <br/>";

                    

                    $file_url_8 = "Technical Passport : <a href='https://www.sar-motorismo.com/test/attachments/$technicalPassport'>See Files Here</a> <br/>";

                    

                    $file_url_9 = "HomologationNo_file: <a href='https://www.sar-motorismo.com/test/attachments/$homologationNo_file'>See Files Here</a> <br/>";

                } 

                

            }



            $email_content .= "$file_url_one\n";

            $email_content .= "$file_url_two\n";

            $email_content .= "$file_url_3\n";

            $email_content .= "$file_url_4\n";

            $email_content .= "$file_url_5\n";

            $email_content .= "$file_url_6\n";

            $email_content .= "$file_url_7\n";

            $email_content .= "$file_url_8\n";

            $email_content .= "$file_url_9\n";

            

            // Send the email

            $headers = "From: info@entries.sar-motorismo.com \r\n";

            $headers .= "Reply-To: info@entries.sar-motorismo.com\r\n";

            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

            if (mail($admin_email, $subject, $email_content, $headers)) {
 // Redireciona para a página de confirmação
    header('Location: confirmacao.html');
    exit();
               
            } else {

                echo "Failed to send email.";

            

            }



        }

        

        

                  



    }

   



}





?>