<?php require_once('header.php'); ?>

<?php
$error_message='';
$success_message='';

if(isset($_POST['form1'])){

    $valid=1;

    if(empty(trim($_POST['product_name']??''))){
        $valid=0;
        $error_message.='Product name can not be empty<br>';
    }

    if(empty(trim($_POST['product_slug']??''))){
        $valid=0;
        $error_message.='Slug can not be empty<br>';
    }

    if(empty($_POST['top_category_id']??'')){
        $valid=0;
        $error_message.='Category can not be empty<br>';
    }

    $final_name='';

    if(isset($_FILES['photo']) && $_FILES['photo']['name']!=''){

        $path=$_FILES['photo']['name'];
        $path_tmp=$_FILES['photo']['tmp_name'];

        if($_FILES['photo']['error']!==UPLOAD_ERR_OK){

            $valid=0;
            $error_message.='Product image upload failed. Error code: '.$_FILES['photo']['error'].'<br>';

        }else{

            $ext=strtolower(pathinfo($path,PATHINFO_EXTENSION));

            $allowed_ext=['jpg','jpeg','png','gif','webp'];

            if(!in_array($ext,$allowed_ext,true)){

                $valid=0;
                $error_message.='You must upload a jpg, jpeg, gif, png, or webp file<br>';

            }else{

                $final_name='product_'.time().'_'.uniqid().'.'.$ext;

                $upload_dir=dirname(__DIR__).DIRECTORY_SEPARATOR.'admin/assets'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'products'.DIRECTORY_SEPARATOR;

                if(!is_dir($upload_dir)){
                    if(!mkdir($upload_dir,0777,true)){
                        $valid=0;
                        $error_message.='Unable to create product image directory.<br>';
                    }
                }

                $upload_path=$upload_dir.$final_name;

                if($valid==1 && !move_uploaded_file($path_tmp,$upload_path)){
                    $valid=0;
                    $error_message.='Failed to move product image.<br>';
                }
            }
        }

    }else{

        $valid=0;
        $error_message.='Please select a product image<br>';
    }

    $final_brochure='';

    if(isset($_FILES['brochure']) && $_FILES['brochure']['name']!=''){

        $brochure_name=$_FILES['brochure']['name'];
        $brochure_tmp=$_FILES['brochure']['tmp_name'];

        if($_FILES['brochure']['error']!==UPLOAD_ERR_OK){

            $valid=0;
            $error_message.='Brochure upload failed. Error code: '.$_FILES['brochure']['error'].'<br>';

        }else{

            $brochure_ext=strtolower(pathinfo($brochure_name,PATHINFO_EXTENSION));

            if($brochure_ext!=='pdf'){

                $valid=0;
                $error_message.='Brochure must be a PDF file<br>';

            }else{

                $final_brochure='brochure_'.time().'_'.uniqid().'.pdf';

                $brochure_dir=dirname(__DIR__).DIRECTORY_SEPARATOR.'pdf'.DIRECTORY_SEPARATOR;

                if(!is_dir($brochure_dir)){
                    if(!mkdir($brochure_dir,0777,true)){
                        $valid=0;
                        $error_message.='Unable to create brochure directory.<br>';
                    }
                }

                $brochure_path=$brochure_dir.$final_brochure;

                if($valid==1 && !move_uploaded_file($brochure_tmp,$brochure_path)){
                    $valid=0;
                    $error_message.='Failed to upload brochure.<br>';
                }
            }
        }
    }

    $applications=[];

    $keys=$_POST['application_key']??[];
    $values=$_POST['application_value']??[];

    if(is_array($keys) && is_array($values)){

        foreach($keys as $index=>$key){

            $key=trim($key);
            $value=trim($values[$index]??'');

            if($key!=='' && $value!==''){
                $applications[$key]=$value;
            }
        }
    }

    $application_json=json_encode(
        $applications,
        JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES
    );

    if($application_json===false){
        $valid=0;
        $error_message.='Unable to save application data.<br>';
    }

    $gallery=[];

    if($final_name!=''){
        $gallery[]='assets/images/products/'.$final_name;
    }

    $gallery_json=json_encode(
        $gallery,
        JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES
    );

    $featured=isset($_POST['featured'])?1:0;

    $content=trim($_POST['content']??'');
    $description=trim($_POST['description']??'');

    if($valid==1){

        try{

            $statement=$pdo->prepare("
                INSERT INTO tbl_service
                (
                    top_category_id,
                    product_name,
                    product_slug,
                    short_description,
                    description,
                    content,
                    main_image,
                    gallery,
                    application,
                    brochure,
                    featured,
                    status,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    NOW(),
                    NOW()
                )
            ");

            $statement->execute([

                (int)$_POST['top_category_id'],

                trim($_POST['product_name']),

                trim($_POST['product_slug']),

                trim($_POST['short_description']??''),

                $description,

                $content,

                $final_name,

                $gallery_json,

                $application_json,

                $final_brochure!=''
                    ?'pdf/'.$final_brochure
                    :null,

                $featured,

                1
            ]);

            $success_message='Product is added successfully!';

            unset($_POST['product_name']);
            unset($_POST['product_slug']);
            unset($_POST['top_category_id']);
            unset($_POST['content']);
            unset($_POST['description']);
            unset($_POST['short_description']);
            unset($_POST['application_key']);
            unset($_POST['application_value']);

        }catch(PDOException $e){

            $valid=0;

            $error_message='Database Error: '.htmlspecialchars(
                $e->getMessage(),
                ENT_QUOTES,
                'UTF-8'
            ).'<br>';
        }
    }
}
?>

<section class="content-header">
    <div class="content-header-left">
        <h1>Add Product</h1>
    </div>

    <div class="content-header-right">
        <a href="service.php" class="btn btn-primary btn-sm">View All</a>
    </div>
</section>

<section class="content">

    <div class="row">

        <div class="col-md-12">

            <?php if(!empty($error_message)): ?>
                <div class="callout callout-danger">
                    <p><?php echo $error_message; ?></p>
                </div>
            <?php endif; ?>

            <?php if(!empty($success_message)): ?>
                <div class="callout callout-success">
                    <p><?php echo $success_message; ?></p>
                </div>
            <?php endif; ?>

            <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">

                <div class="box box-info">

                    <div class="box-body">

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Category <span>*</span>
                            </label>

                            <div class="col-sm-6">

                                <select name="top_category_id" class="form-control" required>

                                    <option value="">Select Category</option>

                                    <?php

                                    $statement=$pdo->prepare("
                                        SELECT id,top_category_name
                                        FROM tbl_top_category
                                        WHERE status=1
                                        ORDER BY top_category_name ASC
                                    ");

                                    $statement->execute();

                                    $categories=$statement->fetchAll(PDO::FETCH_ASSOC);

                                    foreach($categories as $row){

                                        $selected='';

                                        if(
                                            isset($_POST['top_category_id']) &&
                                            $_POST['top_category_id']==$row['id']
                                        ){
                                            $selected='selected';
                                        }

                                    ?>

                                        <option
                                            value="<?php echo (int)$row['id']; ?>"
                                            <?php echo $selected; ?>>
                                            <?php echo htmlspecialchars($row['top_category_name'],ENT_QUOTES,'UTF-8'); ?>
                                        </option>

                                    <?php } ?>

                                </select>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Product Name <span>*</span>
                            </label>

                            <div class="col-sm-6">

                                <input
                                    type="text"
                                    autocomplete="off"
                                    class="form-control"
                                    name="product_name"
                                    placeholder="Automatic Powder Coating Plant"
                                    value="<?php echo isset($_POST['product_name'])?htmlspecialchars($_POST['product_name'],ENT_QUOTES,'UTF-8'):''; ?>">

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Slug <span>*</span>
                            </label>

                            <div class="col-sm-6">

                                <input
                                    type="text"
                                    autocomplete="off"
                                    class="form-control"
                                    name="product_slug"
                                    placeholder="automatic-powder-coating-plant"
                                    value="<?php echo isset($_POST['product_slug'])?htmlspecialchars($_POST['product_slug'],ENT_QUOTES,'UTF-8'):''; ?>">

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Short Description
                            </label>

                            <div class="col-sm-8">

                                <textarea
                                    class="form-control"
                                    name="short_description"
                                    rows="4"
                                    placeholder="Short product description"><?php echo isset($_POST['short_description'])?htmlspecialchars($_POST['short_description'],ENT_QUOTES,'UTF-8'):''; ?></textarea>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Description <span>*</span>
                            </label>

                            <div class="col-sm-8">

                                <textarea
                                    class="form-control"
                                    name="description"
                                    id="editor2"><?php echo isset($_POST['description'])?$_POST['description']:''; ?></textarea>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Content
                            </label>

                            <div class="col-sm-8">

                                <textarea
                                    class="form-control"
                                    name="content"
                                    id="editor1"><?php echo isset($_POST['content'])?$_POST['content']:''; ?></textarea>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Applications
                            </label>

                            <div class="col-sm-8">

                                <div id="application-wrapper">

                                    <div class="application-row row" style="margin-bottom:10px;">

                                        <div class="col-sm-5">

                                            <input
                                                type="text"
                                                name="application_key[]"
                                                class="form-control"
                                                placeholder="Application">

                                        </div>

                                        <div class="col-sm-5">

                                            <input
                                                type="text"
                                                name="application_value[]"
                                                class="form-control"
                                                placeholder="Value">

                                        </div>

                                        <div class="col-sm-2">

                                            <button
                                                type="button"
                                                class="btn btn-success add-application">
                                                +
                                            </button>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Product Image <span>*</span>
                            </label>

                            <div class="col-sm-9">

                                <input
                                    type="file"
                                    name="photo"
                                    accept=".jpg,.jpeg,.png,.gif,.webp"
                                    required>

                                <p class="help-block">
                                    JPG, JPEG, PNG, GIF or WEBP
                                </p>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Brochure
                            </label>

                            <div class="col-sm-9">

                                <input
                                    type="file"
                                    name="brochure"
                                    accept=".pdf">

                                <p class="help-block">
                                    PDF only
                                </p>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Featured
                            </label>

                            <div class="col-sm-6">

                                <label>

                                    <input
                                        type="checkbox"
                                        name="featured"
                                        value="1">

                                    Featured Product

                                </label>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label"></label>

                            <div class="col-sm-6">

                                <button
                                    type="submit"
                                    class="btn btn-success"
                                    name="form1"
                                    value="1">
                                    Submit
                                </button>

                            </div>

                        </div>

                    </div>

                </div>

            </form>

        </div>

    </div>

</section>

<script>
document.addEventListener('DOMContentLoaded',function(){

    const wrapper=document.getElementById('application-wrapper');

    if(!wrapper)return;

    wrapper.addEventListener('click',function(event){

        const addButton=event.target.closest('.add-application');

        if(addButton){

            const row=document.createElement('div');

            row.className='application-row row';
            row.style.marginBottom='10px';

            row.innerHTML=`
                <div class="col-sm-5">
                    <input type="text" name="application_key[]" class="form-control" placeholder="Application">
                </div>
                <div class="col-sm-5">
                    <input type="text" name="application_value[]" class="form-control" placeholder="Value">
                </div>
                <div class="col-sm-2">
                    <button type="button" class="btn btn-danger remove-application">-</button>
                </div>
            `;

            wrapper.appendChild(row);

            return;
        }

        const removeButton=event.target.closest('.remove-application');

        if(removeButton){

            const row=removeButton.closest('.application-row');

            if(row)row.remove();

        }

    });

});
</script>

<?php require_once('footer.php'); ?>