<?php
header("Content-Type: application/json; charset=UTF-8");
include_once 'db_connect.php';

// استقبال البيانات
$json = json_decode(file_get_contents("php://input"), true);

if ($json) {
    try {
        $conn->beginTransaction();

        $hashed_password = password_hash($json['password'], PASSWORD_DEFAULT);

        // تأكد من أن أسماء الحقول هنا (full_name, email, etc) تطابق تماماً جدول users
        $stmt = $conn->prepare("INSERT INTO users (full_name, email, phone, password, city, address, role_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        
        $role_id = 10;
        $status = 'active';

        $stmt->execute([
            $json['full_name'], 
            $json['email'], 
            $json['phone'], 
            $hashed_password, 
            $json['city'], 
            $json['address'], 
            $role_id,
            $status
        ]);

        $conn->commit();
        echo json_encode(["status" => "success", "message" => "Representative added"]);

    } catch (Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollBack();
        }
        // هذا السطر سيطبع لك الخطأ الحقيقي (مثل اسم حقل خطأ) في الـ Debug Console في فلاتر
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid JSON received"]);
}
?>