<?php
// --- PHP Backend Logic ---
// This part of the script will process the form submission
// and insert the data into the MySQL database.

// Configuration variables for your database connection.
// IMPORTANT: Please fill these in with your actual database details.
$servername = "localhost"; // e.g., "localhost" or your database host
$username = "wintelsoft_vinod"; // e.g., "root"
$password = "vinodbhaskar69*"; // e.g., "" (empty for no password)
$dbname = "wintelsoft_svf"; // e.g., "company_db"

// Define variables to store user input and status messages.
$process_code = $process_name = $process_group = $rate = $unit_of_measurement = "";
$message = "";
$is_success = false;

// Check if the form was submitted using the POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validate and sanitize user input to prevent security issues.
    $process_code = filter_input(INPUT_POST, 'process_code', FILTER_SANITIZE_STRING);
    $process_name = filter_input(INPUT_POST, 'process_name', FILTER_SANITIZE_STRING);
    $process_group = filter_input(INPUT_POST, 'process_group', FILTER_SANITIZE_STRING);
    $rate = filter_input(INPUT_POST, 'rate', FILTER_VALIDATE_FLOAT);
    $unit_of_measurement = filter_input(INPUT_POST, 'unit_of_measurement', FILTER_SANITIZE_STRING);

    // Check if any required fields are missing.
    if (!$process_code || !$process_name || !$process_group || $rate === false || !$unit_of_measurement) {
        $message = "Please fill out all the fields correctly.";
        $is_success = false;
    } else {
        // Create a new MySQLi connection.
        $conn = new mysqli($servername, $username, $password, $dbname);

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

        // --- Uniqueness Check for process_code ---
        $check_sql = "SELECT process_code FROM processes WHERE process_code = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("s", $process_code);
        $check_stmt->execute();
        $check_stmt->store_result();

        if ($check_stmt->num_rows > 0) {
            $message = "Error: A process with this code already exists. Process codes must be unique.";
            $is_success = false;
        } else {
            // Use a prepared statement to prevent SQL injection.
            // The "?" placeholders will be replaced with actual values safely.
            $sql = "INSERT INTO processes (process_code, process_name, process_group, rate, unit_of_measurement) VALUES (?, ?, ?, ?, ?)";
            
            // Prepare the statement.
            $stmt = $conn->prepare($sql);
            
            // Bind parameters to the statement.
            // "s" for string, "d" for double (float).
            $stmt->bind_param("sssds", $process_code, $process_name, $process_group, $rate, $unit_of_measurement);

            // Execute the statement and check if it was successful.
            if ($stmt->execute()) {
                $message = "New record created successfully!";
                $is_success = true;
            } else {
                $message = "Error: " . $stmt->error;
                $is_success = false;
            }

            // Close the statement and connection.
            $stmt->close();
        }

        $check_stmt->close();
        $conn->close();
    }
}
?>

<!-- --- HTML Frontend Code --- -->
<!-- This part of the script contains the beautiful, responsive data entry form. -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Process Master</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
        
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .container {
            max-width: 800px;
            margin: 40px auto;
            background-color: #ffffff;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        h2 {
            text-align: center;
            color: #ffffff;
            background-color: #3498db;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            font-weight: 700;
            letter-spacing: 1px;
        }

        .alert-message {
            text-align: center;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-weight: bold;
        }

        .alert-error {
            background-color: #e74c3c;
            color: white;
        }

        .alert-success {
            background-color: #2ecc71;
            color: white;
        }

        .form-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .form-table td {
            padding: 15px;
            vertical-align: top;
        }

        .form-table td:first-child {
            width: 30%;
            text-align: right;
            font-weight: bold;
            padding-right: 20px;
            color: #555;
        }

        .form-table input[type="text"],
        .form-table input[type="date"],
        .form-table input[type="number"],
        .form-table textarea,
        .form-table input[type="file"],
        .form-table select {
            width: 50%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 16px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        .form-table textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-table input:focus,
        .form-table textarea:focus,
        .form-table select:focus {
            border-color: #3498db;
            box-shadow: 0 0 8px rgba(52, 152, 219, 0.2);
            outline: none;
        }
        
        .submit-container {
            text-align: center;
            padding-top: 20px;
        }

        input[type="submit"] {
            background-color: #2ecc71;
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 18px;
            font-weight: bold;
            transition: background-color 0.3s, transform 0.2s;
        }

        input[type="submit"]:hover {
            background-color: #27ae60;
            transform: translateY(-2px);
        }

        .view-link {
            display: block;
            text-align: center;
            margin-top: 20px;
        }

        .view-link a {
            color: #3498db;
            text-decoration: none;
            font-weight: bold;
        }

        .view-link a:hover {
            text-decoration: underline;
        }

        /* Responsive design */
        @media (max-width: 600px) {
            .form-table td {
                display: block;
                width: 100%;
                text-align: left !important;
                padding: 10px 0;
            }
            .form-table td:first-child {
                padding-right: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Process Master</h2>
        
        <?php if ($message): ?>
            <div class="alert-message <?php echo $is_success ? 'alert-success' : 'alert-error'; ?>">
                <p><?php echo htmlspecialchars($message); ?></p>
            </div>
        <?php endif; ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
            <table class="form-table">
                <tbody>
                    <!-- Process Code Field -->
                    <tr>
                        <td><label for="process_code">Process Code</label></td>
                        <td>
                            <input type="text" id="process_code" name="process_code" required placeholder="e.g., PROC-001">
                        </td>
                    </tr>
                    
                    <!-- Process Name Field -->
                    <tr>
                        <td><label for="process_name">Process Name</label></td>
                        <td>
                            <input type="text" id="process_name" name="process_name" required placeholder="e.g., Product Assembly">
                        </td>
                    </tr>
                    
                    <!-- Process Group Field -->
                    <tr>
                        <td><label for="process_group">Process Group</label></td>
                        <td>
                            <input type="text" id="process_group" name="process_group" required placeholder="e.g., Manufacturing">
                        </td>
                    </tr>

                    <!-- Rate Field -->
                    <tr>
                        <td><label for="rate">Rate</label></td>
                        <td>
                            <input type="number" id="rate" name="rate" step="0.01" required placeholder="e.g., 150.75">
                        </td>
                    </tr>

                    <!-- Unit of Measurement Field -->
                    <tr>
                        <td><label for="unit_of_measurement">Unit of Measurement</label></td>
                        <td>
                            <select id="unit_of_measurement" name="unit_of_measurement" required>
                                <option value="" disabled selected>Select a unit</option>
                                <option value="Cu.Ft">Cubic Ft</option>    
                                <option value="Rupees">Rupees</option>
                                <option value="Hrs">Hrs</option>
                                <option value="Day">Day</option>
                                <option value="Kg">Kg</option>
                                <option value="Nos">Nos</option>
                                <option value="Litters">Litters</option>
                                <option value="Unit">Unit</option>
                                <option value="Pcs">Pcs</option>
                            </select>
                        </td>
                    </tr>

                    <!-- Submit Button -->
                    <tr>
                        <td colspan="2" class="submit-container">
                            <input type="submit" value="Add Process">
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>

        <div class="view-link">
            <a href="view_process.php">View All Processes</a>
        </div>
    </div>
</body>
</html>
