<?php
include('../config/function.php'); // Ensure this file includes the database connection setup
session_start(); // Ensure the session is started

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Helper function to validate and sanitize input
    function validateInput($input) {
        return htmlspecialchars(trim($input));
    }

    // Extract and validate data from the contract form
    $contractNo = validateInput($_POST['contractNo']);
    $clientID = validateInput($_POST['clientID']);
    $projectCoord = validateInput($_POST['projectCoord']);
    $teamLead = validateInput($_POST['teamLead']);
    $contractName = validateInput($_POST['contractName']);
    $contractAmount = validateInput($_POST['contractAmount']);
    $taxDetails = validateInput($_POST['taxDetails']);
    $clientPONumber = validateInput($_POST['clientPONumber']);
    $startDate = validateInput($_POST['startDate']);
    $endDate = validateInput($_POST['endDate']);

    // Check the database connection
    if ($conn === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Insert contract data into the contracts table using prepared statements
    $insertContractQuery = $conn->prepare("INSERT INTO contracts (contractNo, contractName, contractAmt, taxDetails, clientPONo, ncstartDate, ncendDate)
                                           VALUES (?, ?, ?, ?, ?, ?, ?)");
    $insertContractQuery->bind_param('sssssss', $contractNo, $contractName, $contractAmount, $taxDetails, $clientPONumber, $startDate, $endDate);

    if ($insertContractQuery->execute()) {
        // Retrieve the newly inserted contractID
        $lastInsertID = $conn->insert_id;

        // Insert project data into the projects table using prepared statements
        $insertProjectQuery = $conn->prepare("INSERT INTO projects (contractID, clientID, projectName, contractValue, projectCoord, teamLead)
                                              VALUES (?, ?, ?, ?, ?, ?)");
        $insertProjectQuery->bind_param('iissss', $lastInsertID, $clientID, $contractName, $contractAmount, $projectCoord, $teamLead);

        if ($insertProjectQuery->execute()) {
            $projectID = $conn->insert_id; // Get the newly inserted projectID
            $_SESSION['status'] = 'Contract and Project created successfully.';

            // Insert milestone data into the milestones table
            $insertMilestoneQuery = $conn->prepare("INSERT INTO milestones (milestoneName, milestoneValue, completionDate, projectID)
                                                    VALUES (?, ?, ?, ?)");
            $milestoneName = "Full Contract"; // Milestone name as specified
            $completionDate = $endDate; // Assuming the end date is the completion date
            $insertMilestoneQuery->bind_param('ssss', $milestoneName, $contractAmount, $completionDate, $projectID);

            if ($insertMilestoneQuery->execute()) {
                $_SESSION['status'] .= ' Milestone created successfully.';

                // Insert ncmilestone data into the ncmilestones table
                $insertNcmilestoneQuery = $conn->prepare("INSERT INTO ncmilestones (milestone, expectedDateBilling, expectedAmt, contractID)
                                                          VALUES (?, ?, ?, ?)");
                $ncmilestoneName = "Full Contract"; // Milestone name for ncmilestones
                $expectedDateBilling = $endDate; // Assuming the end date is the expected billing date
                $insertNcmilestoneQuery->bind_param('ssis', $ncmilestoneName, $expectedDateBilling, $contractAmount, $lastInsertID);

                if ($insertNcmilestoneQuery->execute()) {
                    $_SESSION['status'] .= ' NC Milestone created successfully.';

                    // Send email to Project Coordinator and Team Leader
                    // Fetch email addresses
                    $getEmailsQuery = $conn->prepare("SELECT email FROM users WHERE userID IN (?, ?)");
                    $getEmailsQuery->bind_param('ii', $projectCoord, $teamLead);
                    $getEmailsQuery->execute();
                    $emailsResult = $getEmailsQuery->get_result();
                    $emails = [];
                    while ($row = $emailsResult->fetch_assoc()) {
                        $emails[] = $row['email'];
                    }

                    // Additional CC email addresses
                    $ccEmails = ['accounts@newconceptinfosys.com', 'raghavan.s@newconceptinfosys.com', 'uma.seth@newconceptinfosys.com'];

                    // Email settings
                    $fromEmail = 'accounts@newconceptinfosys.com';
                    $replyToEmail = 'uma.seth@newconceptinfosys.com';
                    $subject = 'New Contract Created';
                    $message = "A new contract has been created.\n\n" .
                               "Contract No: $contractNo\n" .
                               "Contract Name: $contractName\n" .
                               "Contract Amount: $contractAmount\n" .
                               "Start Date: $startDate\n" .
                               "End Date: $endDate\n\n" .
                               "Please update the Contract Milestones at " .
                               "https://newconceptidbms.com/admin/contracts-view.php?contractID=$lastInsertID\n";
                    $headers = "From: $fromEmail\r\n" .
                               "Reply-To: $replyToEmail\r\n";

                    // Add CC recipients
                    foreach ($ccEmails as $ccEmail) {
                        $headers .= "Cc: $ccEmail\r\n";
                    }

                    $headers .= 'X-Mailer: PHP/' . phpversion();

                    // Send email to each recipient
                    foreach ($emails as $email) {
                        mail($email, $subject, $message, $headers);
                    }
                    $_SESSION['status'] .= ' Emails sent successfully.';
                } else {
                    $_SESSION['status'] = 'Error creating NC Milestone: ' . $insertNcmilestoneQuery->error;
                    error_log("Error creating NC Milestone: " . $insertNcmilestoneQuery->error);
                }
            } else {
                $_SESSION['status'] = 'Error creating Milestone: ' . $insertMilestoneQuery->error;
                error_log("Error creating Milestone: " . $insertMilestoneQuery->error);
            }
        } else {
            $_SESSION['status'] = 'Error creating Project: ' . $insertProjectQuery->error;
            error_log("Error creating Project: " . $insertProjectQuery->error);
        }
    } else {
        $_SESSION['status'] = 'Error creating Contract: ' . $insertContractQuery->error;
        error_log("Error creating Contract: " . $insertContractQuery->error);
    }

    $insertContractQuery->close();
    $insertProjectQuery->close();
    $insertMilestoneQuery->close();
    $insertNcmilestoneQuery->close();
    $conn->close();

    header('Location: contracts.php');
    exit();
} else {
    // If the form was not submitted via POST, redirect to the contracts page
    header('Location: contracts.php');
    exit();
}
?>
