<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'connection.php'; // DB connection file
// require 'cors.php';       // CORS handler

// Force JSON response for all errors
error_reporting(E_ALL);
ini_set('display_errors', 0);

set_exception_handler(function ($e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    exit;
});
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    echo json_encode(["status" => "error", "message" => "$errstr in $errfile:$errline"]);
    exit;
});

$response = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['com_name'], $_POST['mob_num'], $_POST['off_num'], $_POST['email'], $_POST['user_name'], $_POST['password'], $_POST['gst_no'], $_POST['street'], $_POST['city'], $_POST['district'], $_POST['pincode'])) {
        
        $companyName = $_POST['com_name'];
        $offNum = $_POST['off_num'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $district = $_POST['district'];
        $mobile = $_POST['mob_num'];
        $email = $_POST['email'];
        $gst = $_POST['gst_no'];
        $userName = $_POST['user_name'];
        $password = $_POST['password'];
        $pincode = $_POST['pincode'];
       /* $registrationMobile = $_POST['registrationMobile'];
        $registrationMailID = $_POST['registrationMailID'];*/
        
         // Determine which mobile and email to check first
        $checkMobile = $mobile;
        $checkEmail = $email;
        
        /*$checkMobile = !empty($registrationMobile) ? $registrationMobile : $mobile;
        $checkEmail = !empty($registrationMailID) ? $registrationMailID : $email;*/

        // Check if registration exists
        $checkStmt = $conn->prepare("SELECT id FROM registration WHERE mob_num = ? OR email = ?");
         $checkStmt->bind_param("ss", $checkMobile, $checkEmail);
        $checkStmt->execute();
        $result = $checkStmt->get_result();

        if ($row = $result->fetch_assoc()) {
            $registrationID = $row['id']; 
        } else {
            // Insert new registration
            $regStmt = $conn->prepare("INSERT INTO registration (mob_num, email, com_name) VALUES (?, ?, ?)");
            $regStmt->bind_param("sss", $mobile, $email, $companyName);
            if (!$regStmt->execute()) {
                echo json_encode(["success" => false, "message" => "Error inserting into registration: " . $regStmt->error]);
                exit;
            }
            $registrationID = $conn->insert_id;
            $regStmt->close();
        }
        $checkStmt->close();

        // Insert into company table
         // Prepare insert
        $companystmt = $conn->prepare("INSERT INTO company 
            (reg_id, com_name, mob_num, off_num, email, user_name, password, gst_no, street, city, district, pincode, logo) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        if (!$companystmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        $companystmt->bind_param(
            "issssssssssss",
            $registrationID,
            $companyName,
            $mobile,
            $offNum,
            $email,
            $userName,
            $password,
            $gst,
            $street,
            $city,
            $district,
            $pincode,
            $logoBase64
        );

        if ($companystmt->execute()) {
            $response = ["status" => "success", "message" => "Registration successful"];
        } else {
            $response = ["status" => "error", "message" => "DB Error: " . $companystmt->error];
        }
        $companyId = $conn->insert_id;
        $companystmt->close();

        // Insert into user table
        $userStmt = $conn->prepare("INSERT INTO staff (reg_id, com_id, name, user_type, user_name, password, permissions) VALUES (?, ?, ?, 'admin', ?, ?, 'All')");
        $userStmt->bind_param("iisss", $registrationID, $companyId, $companyName, $userName, $password);
        if (!$userStmt->execute()) {
            echo json_encode(["success" => false, "message" => "Error inserting into user table: " . $userStmt->error]);
            exit;
        }
        $uid = $conn->insert_id; // Capture the UID from user table
    
        $userStmt->close();
        // Insert predefined ledger groups
        $ledgerGroups = [
            'Bank', 'Expenses', 'Cash in hand', 'Broker', 'Others', 'Income', 'Capital A/C', 
            'Sundry Debtors', 'Customer', 'Sundry Creditors', 'Supplier', 'Current Assets', 
            'Loan And Advances', 'Fixed Assets', 'Loans (Liability)', 'Unsecured Loans', 
            'Profit And Loss Account', 'Expenditure Accounts'
        ];

        $ledgerStmt = $conn->prepare("INSERT INTO ledger_under (com_id, under_name) VALUES (?, ?)");
        foreach ($ledgerGroups as $ledgerName) {
            $ledgerStmt->bind_param("is", $companyId, $ledgerName);
            if (!$ledgerStmt->execute()) {
                echo json_encode(["success" => false, "message" => "Error inserting into ledger_under: " . $ledgerStmt->error]);
                exit;
            }
        }
        $ledgerStmt->close();

 
        echo json_encode(["success" => true, "message" => "Registration successful"]);

    } else {
        echo json_encode(["success" => false, "message" => "Required fields are missing"]);
    }
}


/*if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Collect values from POST
        $reg_id     = $_POST['reg_id'] ?? null;
        $com_id     = $_POST['com_id'] ?? null;
        $com_name   = $_POST['com_name'] ?? null;
        $mob_num    = $_POST['mob_num'] ?? null;
        $off_num    = $_POST['off_num'] ?? null;
        $email      = $_POST['email'] ?? null;
        $user_name  = $_POST['user_name'] ?? null;
        $password   = $_POST['password'] ?? null;
        $gst_no     = $_POST['gst_no'] ?? null;
        $street     = $_POST['street'] ?? null;
        $city       = $_POST['city'] ?? null;
        $district   = $_POST['district'] ?? null;
        $pincode    = $_POST['pincode'] ?? null;
        $logoBase64 = $_POST['logo'] ?? null; // keep as base64 string

        // Validate required fields
        if (empty($com_name) || empty($user_name) || empty($password)) {
            echo json_encode(["status" => "error", "message" => "Missing required fields"]);
            exit;
        }

        // Hash password for security
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

        // Prepare insert
        $stmt = $conn->prepare("INSERT INTO company 
            (reg_id, com_id, com_name, mob_num, off_num, email, user_name, password, gst_no, street, city, district, pincode, logo, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");

        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        $stmt->bind_param(
            "iissssssssssis",
            $reg_id,
            $com_id,
            $com_name,
            $mob_num,
            $off_num,
            $email,
            $user_name,
            $password,
            $gst_no,
            $street,
            $city,
            $district,
            $pincode,
            $logoBase64
        );

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Registration successful"];
        } else {
            $response = ["status" => "error", "message" => "DB Error: " . $stmt->error];
        }

        $stmt->close();
    } catch (Exception $e) {
        $response = ["status" => "error", "message" => "Exception: " . $e->getMessage()];
    }
}*/ else {
    $response = ["status" => "error", "message" => "Invalid request method"];
}

echo json_encode($response);
