<?php
 
use App\Models\Ouvrier;
$ouvriers = Ouvrier::all();

use App\Models\MatierePremiere;
$matieres = MatierePremiere::all();

use App\Models\ArticleChantier;
$articles_chantiers = ArticleChantier::all();

use App\Models\Fournisseur;
$fournisseurs = Fournisseur::all();

use App\Models\ArticleChantierMatiereFournisseur;
$ch_ar_mt_fr = ArticleChantierMatiereFournisseur::all();


use App\Models\Reglement;
$Reglements = Reglement::all();

use App\Models\ModeReglement;
$ModeReglements = ModeReglement::all();

// $ch_ar_mt_fr = ArticleChantierMatiereFournisseur::with('article', 'matierePremiere', 'fournisseur')->get();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affectation</title>
    <link rel="icon" type="text/css" href="{{ asset('images/logo.png') }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" rel="stylesheet">
 
   
    <link rel="stylesheet" href="/css/custom.css">
 
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1000; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
 
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: 10% auto; /* Adjusted to 10% from the top */
    padding: 20px;
    border: 1px solid #888;
    width: 750px; /* Fixed width */
    height: 600px;  /* Fixed height */
    overflow: auto; /* Enable scroll for the modal content */
}
 
/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    text-align:center;
}
 
.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
 
/* The search box */
#searchBox {
    margin-bottom: 20px;
    padding: 10px;
    width: 95%;
    font-size: 16px;
}
 
/* The grid of Articles */
.Article-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}
 
.card2 {
    cursor: pointer;
    flex: 0 1 calc(33% - 20px); /* Adjust the percentage and subtract any margins/padding */
    box-sizing: border-box; /* Include padding and border in the element's total width and height */
    /* margin: 10px; */
    text-align: left;
    border: 1px solid #ccc;
    padding: 4px;
    border-radius: 4px;
    transition: transform 0.2s;
    width: 160px;
}
 
.card2:hover {
    transform: scale(1.05);
}
 
.Article-icon {
    width: 100%;
    height: 50px;
    margin-bottom: 10px;
    /* margin-right: 30px; */
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    padding: 2px;
    font-size: 24px;
}
.status-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
 
.status-badge {
    background-color: #3498db; /* Choose color to match the badge */
    color: white;
    padding: 0.25em 0.75em;
    /* border-radius: 0.5em; Adjust as necessary to match the desired curvature */
    position: relative;
    font-weight: bold; /* Make the text bold */
}
 
.status-badge::after {
    content: '';
    position: absolute;
    right: -16.8px; /* Adjust to match the triangle size */
    top: 50%;
    width: 0;
    height: 0;
    border-style: solid ;
    border-width: 17px 0 17px 17px; /* Adjust to change the size of the triangle */
    border-color: transparent transparent transparent #3498db; /* Match the badge color */
    transform: translateY(-50%);
}
 
.status-checkmark {
    display: inline-block;
    color: blue; /* Checkmark color */
    margin-left: 0.5em;
}
 
.expense-summary {
    display: inline-flex;
    align-items: center;
}
 
.float-right {
    margin-left: auto;
}
.card-header {
    position: relative;
    /* Add other styles for the header as necessary */
}
 
.status-badge {
    position: absolute;
    top: 10px; /* Adjust as needed */
    left: 10px; /* Adjust as needed */
    background-color: #3498db;
    color: white;
    padding: 5px 10px;
    /* border-radius: 5px; */
    display: inline-flex;
    align-items: center;
    font-size: 14px;
    font-weight: bold;
    margin-left: -20px;
    /* padding:  0px 40px; */
}
 
.checkmark-circle {
    background-color: #28a745; /* Checkmark circle color */
    border-radius: 50%;
    width: 20px; /* Adjust size as needed */
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 10px;
    color: white;
}
 
.status-arrow {
    content: "";
    position: absolute;
    right: -10px; /* Half the width of the square root of 2 times the height (for a 45 degree angle) */
    top: 50%;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #3498db;
    transform: translate(0, -50%);
}
 
.fa-check {
    font-size: 10px;
    color: white;
}
.status-badge .status-arrow {
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 20px solid #3498db; /* Match the color with the status badge */
    position: absolute;
    top: -20px; /* Half the height of the arrow */
    right: 0;
    transform: translateX(50%);
}
 
#ArticleGrid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* Three columns */
  grid-gap: 20px; /* Space between cards */
  margin: 0 auto; /* Centering the grid */
}
 
.card2 {
  border: 1px solid #ccc; /* Optional border */
  border-radius: 10px; /* Rounded corners */
  overflow: hidden; /* Ensures the content fits within the borders */
}
 
.Article-icon {
  /* width: 180px; */
  height: 90px; /* Fixed height for the image */
  background-image: linear-gradient(to bottom, blue  ,violet); /* Gradient background */
  display: flex;
  align-items: center;
  justify-content: center;
}
 
.Article-icon i {
  color: white;
  font-size: 2em; /* Larger icon */
}
 
.card2 span {
  display: block;
  text-align: center;
  padding: 10px;
  background-color:  rgba(0, 123, 252 , 0.7);
  border-radius: 4px;
}
.tab-content {
    min-height: 400px; /* Or whatever minimum height is needed */
    height: 600px;  /* Fixed height */

}
 
#AnalyseContent {
    overflow-y: auto; /* Enable vertical scrolling */
    height: 600px; /* Fixed height; adjust as needed */
    
}
 
.chart-container {
    width: 100%; /* Adjust if you want a specific width */
    padding: 10px;
    box-sizing: border-box;
}
 
/* Optional: Style to make sure the canvas sizes are controlled */
.chart-canvas {
  padding-left: 90px;
  padding-right: 90px;
    width: 100% !important;
    height: 100% !important;
    /* aspect-ratio: 2 / 1; This will make the chart maintain a 2:1 aspect ratio */
}
.chart-canvas3 {
  padding-left: 200px;
  padding-right: 200px;
  width: 1000px!important; 
  height: 200px!important; 
    /* width: 100% !important;
    height: 100% !important; */
    /* aspect-ratio: 2 / 1; This will make the chart maintain a 2:1 aspect ratio */
}


.chart-canvas2 {
  padding-left: 300px;
  padding-right: 300px;
    width: 100% !important;
    height: 100% !important;
    /* aspect-ratio: 2 / 1; This will make the chart maintain a 2:1 aspect ratio */
}
.modal-backdrop {
      /* bug fix - no overlay */    
      display: none;    
}
 
.modal{
    /* bug fix - custom overlay */  
    background-color: rgba(10,10,10,0.45);
}
.tab-content, .active-content {
  width: 100%;
  margin-top:20px;
  max-height: 450px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  border: 1px solid #ccc;
}
#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
    position:relative;
    width:300px;
    min-height:100px;
    margin-top:50px;
    border:1px solid #666;
    background-color:#fff;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#modalContainer > #alertBox {
    position:fixed;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:#3073BB;
    color:#FFF;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#357EBD;
    border-radius: 3px;
    text-decoration:none;
}

/* unrelated styles */

#mContainer {
    position:relative;
    width:600px;
    margin:auto;
    padding:5px;
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;
}

h1,h2 {
    margin:0;
    padding:4px;
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;
}

code {
    font-size:1.2em;
    color:#069;
}

#credits {
    position:relative;
    margin:25px auto 0px auto;
    width:350px; 
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;
    height:90px;
    padding-top:4px;
}

#credits img {
    float:left;
    margin:5px 10px 5px 0px;
    border:1px solid #000000;
    width:80px;
    height:79px;
}

.important {
    background-color:#F5FCC8;
    padding:2px;
}

code span {
    color:green;
}
#fournisseurModal .modal-dialog {
    max-width: 650px; /* Set the maximum width of the modal */
    margin: 30px auto; /* This will center the modal horizontally */
  }
  .result {
    padding: 10px;
    color: white;
    text-align: center;
    margin-top: 10px;
  }
  .positive-result {
    background-color: green;
  }
  .negative-result {
    background-color: red;
  }
.card-header {
    position: relative; /* Ensures that absolute positioning is relative to this container */
    padding: 10px; /* Adjust as needed */
}

.status-badge {
    display: flex;
    align-items: center; /* Aligns items vertically in the center */
    position: absolute; /* Positions your status badge */
    top: 10px; /* Adjust as needed */
    left: 10px; /* Adjust as needed */
    background: #3498db; /* The blue background */
    padding: 5px 10px; /* Adjust as needed */
    /* border-radius: 5px; Rounded corners */
    color: white; /* Text color */
    font-weight: bold; /* Bold text */
}

.checkmark-circle {
    display: inline-flex;
    align-items: center; /* Centers the icon vertically */
    justify-content: center; /* Centers the icon horizontally */
    margin-left: 10px; /* Adjust space between the text and icon */
    height: 24px; /* Adjust as needed */
    width: 24px; /* Adjust as needed */
    background-color: #3498db; /* Match the status badge color */
    border-radius: 50%; /* Circle shape */
}

.fas.fa-hourglass-start {
    color: white; /* Icon color */
}

.export-pdf {
    float: right; /* Aligns the PDF export link to the right */
    margin: 10px; /* Adjust as needed */
}

.export-link {
    display: inline-block;
    padding: 8px 12px;
    background-color: #007bff;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    font-weight: bold;
    text-align: center; /* Centers the text inside the link */
}
.status-badge::before {
    /* right: -1px;  */
    content: '';
    position: absolute;
    bottom: -9.7px; /* Position the triangle at the bottom */
    left: 0.2px; /* Align the triangle to the left side */
    border-top: 9px solid #3577b9; /* Color of the triangle should match the badge */
    border-right: 9px solid transparent;
    border-left: 9px solid transparent;
    border-width: 10.03px 0 10.09px 9.09px; /* Adjust to change the size of the triangle */

}

/* added recently */
.modal {
  /* display: flex; */
  justify-content: center;
  align-items: center;
  position: fixed; /* or 'absolute' depending on how you want to position the modal */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5); /* Dimmed background */
}

.modal-content {
  max-width: 600px; /* or your preferred max width */
  width: 90%; /* or your preferred width */
  margin: auto; /* this will take precedence when the screen is small */
  background: #fff;
  padding: 20px;
  border-radius: 5px; /* Optional: if you want rounded corners */
  position: relative; /* Allows you to absolutely position elements inside like the close button */
  box-sizing: border-box; /* Makes sure padding doesn't affect width */
}

</style>
 
</head>
<body>
@if(session('error'))
    <div class="alert alert-danger">
        {{ session('error') }}
    </div>
@endif
 
@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
 
<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <b>Chantier N° {{ $chantier->id }} :  {{ ucfirst($chantier->nom) }}</b>
                </div>
                <div class="card-header">
                    <div class="status-badge">
                        <span class="status-text">En cours</span>
    <div class="checkmark-circle" style=" background-color:#3498db;">
        <i class="fas fa-hourglass-start" style="color: white;"></i> <!-- Updated class for the hourglass icon -->
    </div>
    <!-- <div class="status-arrow"></div> -->
</div>
<div style="width:126px;margin-left:auto;">
  <a style="display: inline-block; padding: 8px 12px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px; font-weight: bold; margin-right: 10px;" href="/export-chantier-pdf/{{$chantier->id}}" class="dropdown-item">
    <i class="fas fa-file-pdf"></i> Export PDF
</a>  
</div>
 
 
              <!-- Additional content if needed -->
              <br>
 <!-- export pdf/excel -->
<!-- <div> -->
<!-- <div class="dropdown" style="text-align:right;"> -->
  <!-- <button class="btn btn-secondary dropdown-toggle" type="button" id="exportDropdownButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> -->
    <!-- Exporter -->
  <!-- </button> -->
  <!-- <div class="dropdown-menu" aria-labelledby="exportDropdownButton"> -->
    <!-- <a style="text-align:right;" class="dropdown-item" href="/export-chantier-pdf/{{$chantier->id}}"><i class="fas fa-file-pdf"></i> Export PDF</a> -->
    <!-- <a class="dropdown-item" href="/export-chantiers"><i class="fas fa-file-csv"></i> Export texte (csv)</a> -->
  <!-- </div> -->
<!-- </div> -->
<!-- <div> -->


  <div style="font-family: Arial, sans-serif; padding-left: 80px;">
      <!-- Location -->
      <div>
          <i class="fas fa-map-pin" style="color: #3498db;"></i>
          <strong>Localisation: </strong>&nbsp;<span>{{ ucfirst($chantier->localisation) }}</span>
      </div>
      <!-- Name -->
      <div>
          <i class="fas fa-building" style="color: #2ecc71;"></i>
          <strong>Nom de projet: </strong>&nbsp;<span>{{ ucfirst($chantier->nom) }}</span>
      </div>
      <!-- client -->
      <div>
       <i class="fas fa-user" style="color: #45B39D;"></i>
          <strong>Nom client: </strong>&nbsp;<span>{{ ucfirst($chantier->nom_client) }}</span>
      </div>
      <!-- Start Date -->
      <div>
          <i class="fas fa-calendar-alt" style="color: #e74c3c;"></i>
          <strong>Date debut: </strong>&nbsp;<span>{{ $chantier->date_debut }}</span>
      </div>
      <!-- budget -->
      <!--<div>
       <i class="fas fa-dollar-sign" style="color: #45B39D;"></i>
          <strong>Budget: </strong>&nbsp;<span>{{ $chantier->budget }}</span>
      </div> -->
      <!-- Duration -->
      <div>
          <i class="fas fa-hourglass-half" style="color: #f1c40f;"></i>
          <strong>Duree: </strong>&nbsp;
          <span>
          <!-- Assuming $chantier->date_debut is a DateTime object and you want to calculate duration -->
          @php
              $start_date = new DateTime($chantier->date_debut);
              $now = new DateTime();
              $interval = $start_date->diff($now);
              echo $interval->format('%a Jours');
          @endphp
          </span>
      </div>
  </div>
 
 

 
</div>

@php
$data = [];
$pricet = 0;
$total_prix_estime = 0;
// Calculate the total budget from articles and ouvrier data
foreach ($articles_chantiers as $art) {
    foreach ($ch_ar_mt_fr as $row) {
        if ($row->article_chantier_id == $art->id && $art->chantier_id == $chantier->id) {
            $pricet += $row->prix * $row->qte; // price * quantity from a different dataset
        }
    }
}

// Adding salaries for workers based on days worked
foreach ($ouvrier_chantiers as $ouvrier_chantier) {
    $startDate = \Carbon\Carbon::parse($ouvrier_chantier->pivot->date_debut);
    $endDate = \Carbon\Carbon::parse($ouvrier_chantier->pivot->date_fin);
    $daysWorked = $endDate->diffInDays($startDate);
    $totalPrice = $daysWorked * $ouvrier_chantier->salaire_journalier;
    $pricet += $totalPrice;
}

// Calculate the total estimated price for articles in the current chantier
foreach ($articles_chantiers as $art) {
    if ($art->chantier_id == $chantier->id) {
        $total_prix_estime += $art->prix_estime;
    }
}
@endphp

<!-- Displaying Results -->
<div class="mb-4" id="detail_chantier">
    <span class="float-right" style="padding: 15px; background-color: {{ $total_prix_estime >= $pricet ? '#2ECC71' : 'red' }}; margin-bottom: -24px; border-bottom-right-radius: 3px;">
        <b>{{$pricet}} DH</b>
        <!-- <b>{{ number_format($pricet, 2) }} DH</b> -->

    </span>
    
</div>


 <!-- @php
$result=$total_prix_estime - $pricet;
@endphp
    @if ($result >= 0)
vous etes gagne : {{ $result }} DH
    @else
    vous etes perdu : {{ $result }} DH
    @endif  -->
 </div> 








    </div>
    </div>
    </div>
 
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container mt-12" style="margin-top: 10px;">
 
<div class="card-header card-body" style="text-align:center;">
<div class="" style="display: flex; justify-content: flex-end; align-items: center;">
    <a href="{{ route('chantiers.index') }}" style="color:red; font-size: 24px; padding-right:10px;">
        <i class="fas fa-times"></i>
    </a>
</div>
<ul class="nav nav-tabs card-header-tabs col-md-12">
    
   
    <li class="nav-item">
        <a class="nav-link active" id="articlesTab" data-target="#Articles" href="#"><i class="fas fa-box"></i> Articles</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="ouvrierTab" data-target="#OuvriersContent" href="#"><i class="fas fa-users"></i> Ouvriers</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="fournisseurTab" data-target="#FournisseursContent" href="#"><i class="fas fa-truck"></i> Fournisseurs</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="analyseTab" data-target="#AnalyseContent" href="#"><i class="fas fa-chart-bar"></i> Analyse</a>
    </li>
   
</ul>
<!-- Articles tab content -->
<div id="Articles" class="tab-content active-content" style="display: block;">
    <button class="btn btn-success" id="myBtn">+ Nouvel article</button>
    <br><br>
    <div class="card-body table-responsive">

    <table class="table table-hover">
        <thead>
            <tr>
                <!-- <th>Id</th> -->
                <th>Reference</th>
                <th>Designation</th>
                <th>Unité</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($articles_chantiers  as $article_chantier)
            @if($article_chantier->chantier_id==$chantier->id)
            @foreach($articles  as $art)
            @if($article_chantier->article_id==$art->id)
            <tr>
                <!-- <td>{{ $article_chantier->id }}</td> -->
                <td>{{ $art->ref }}</td>
                <td>{{ $art->designation }}</td>
                <td>{{ $art->unites }}</td>
                <td>
                  <form action="" method="POST">
                    @csrf
                    @method('DELETE')
                    <button type="button"  class="btn btn-danger delete-article-btn" 
                            data-chantier-id="{{ $chantier->id }}" 
                            data-article-id="{{ $article_chantier->article_id}}">
                        <i class="fas fa-trash-alt"></i> 
                    </button>                   
                    <a class="btn btn-info view-article-btn" data-article-chantier-id="{{ $article_chantier->id }}">
                    <i class="far fa-eye"></i>
                    </a>
                    
                    <button type="button" class="btn btn-primary edit-article-btn" data-article-chantier-id="{{ $article_chantier->id }}" data-current-price="{{ $article_chantier->prix_estime }}">
    <i class="fas fa-pencil-alt"></i>
</button>


                    </form></td>
            </tr>
            @endif
            @endforeach
            @endif
            @endforeach
        </tbody>
    </table></div>
</div>
<div id="expenseModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h5><b>Ajouter un nouvel article</b></h5>
        <input type="text" id="searchBox" placeholder="Rechercher...">
        <div id="ArticleGrid" class="Article-grid">
            <!-- Article cards will be dynamically inserted here -->
        </div>
    </div>
</div>

<!-- affecter matiere -->
<div class="modal fade"  id="materialModal" tabindex="-1" aria-labelledby="materialModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="materialModalLabel">Matière Première de l'Article</h5>
        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
          <span class="close" onclick="closeMatiereModal();">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <table class="table" id="materialsTable">
          <thead>
            <tr>
              <!-- <th>article Id</th> -->
              <th>Designation</th>
              <th>Fournisseur</th>
              <th>Numero du bon</th>

              <th>Quantite</th>
              <th>Unité</th>
              <th>Prix/unite</th>
              <!-- <th>Prix TTC</th> -->
              <th>Action</th>
            </tr>
          </thead>
          <tbody> 

          </tbody>
        </table>
        <button type="button" class="btn btn-primary" id="addNewMaterial">+ Nouvelle Matière</button>
      </div>
    </div>
  </div>
</div>
<!--  -->
<!-- <div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <div class="modal-content">
            <div class="modal-header">
            <h4 class="modal-title">détails du budget</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
               
            </div>
            <div class="modal-body">
                <div style="font-weight:bold; font-family:Arial;">
                    <div>{{$chantier->budget }} DH</div>
                    <div> <b>-</b> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;</div>
                    <div>{{ $pricet }} DH</div>
                    <hr style="border-top: 2px solid #000; width:50%;">
                    <div> <b>=</b> &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;</div>
                    <div>&ensp;&ensp;{{ $result }} DH</div>
                </div>

                <div style="text-align:left;margin-top:50px;">
                   
             @if ($result>=0)
        <span style="padding: 15px; color: #2ECC71; margin-bottom: -24px; border-bottom-right-radius: 3px;">
       <b> vous avez gagné : {{ $result }} DH</b></span>

    @else
        <span style="padding: 15px;color: red; margin-bottom: -24px; border-bottom-right-radius: 3px;">
        <b>vous avez perdu : {{ $result }} DH</b></span>
        @endif
                </div>
              
            </div>
            
        </div>

    </div>
</div> -->
<!-- Ouvriers tab content -->
<div id="OuvriersContent" class="tab-content" style="display: none;">
 
    <button class="btn btn-success" onclick="openWorkerModal()">+ Nouvel ouvrier</button>
    <br>
    <br>
    <div class="card-body table-responsive">
    <table class="table table-hover">
        <thead>
            <tr>
                <!-- <th>ID</th> -->
                <th>Nom</th>
                <th>Prénom</th>
                <th>Date de début</th>
                <th>Date de fin</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        @foreach($ouvrier_chantiers as $ouvrier_chantier)
<tr>
    <!-- <td>{{ $ouvrier_chantier->id }}</td> -->
    <td>{{ $ouvrier_chantier->nom }}</td>
    <td>{{ $ouvrier_chantier->prenom }}</td>
    <td>{{ $ouvrier_chantier->pivot->date_debut }}</td>
    <td>{{ $ouvrier_chantier->pivot->date_fin }}</td>
    <td>
        <form action="{{ route('chantiers.deleteWorker', ['chantier_id' => $chantier->id, 'ouvrier_id' => $ouvrier_chantier->id]) }}" method="POST">
            @csrf
            @method('DELETE')
            <button type="submit" class="btn btn-danger" onclick="return confirm('Êtes-vous sûr de vouloir supprimer cette affectation ?')">
                <i class="fas fa-trash-alt"></i>
            </button>
        </form>
    </td>
</tr>
@endforeach
        </tbody>
    </table></div>
</div>
 
<!-- Analyse tab content -->
<div id="AnalyseContent" class="tab-content" style="display: none;">
<!-- <div class="chart-container">
<h3>Article par Année</h3>
<canvas id="salesBarChart" class="chart-canvas2"></canvas>
</div> -->
<div class="row mb-2">
<div class="col-md-6">
<div class="card card-danger">
<div class="card-header">
<h5 class="card-title">Distribution d'Articles</h5>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<canvas id="salesPieChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; padding: 10px;"></canvas>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
 
          </div>
 
    <div class="col-md-6">
<div class="card card-danger">
<div class="card-header">
<h5 class="card-title">Distribution Salaire Ouvriers</h5>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<canvas id="OuvriersChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; padding: 10px;"></canvas>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
 
          </div>
 
          </div>
 
 
 
    <div class="row mb-2">
<div class="col-md-6">
<div class="card card-danger">
<div class="card-header">
<h5 class="card-title">Analyse Fornisseurs</h5>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<canvas id="FornisseursChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; padding: 10px;"></canvas>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
 
          </div>
 
    <div class="col-md-6">
<div class="card card-danger">
<div class="card-header">
<h5 class="card-title">Analyse Matières</h5>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<canvas id="expenditurePerSupplierChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; padding: 10px;"></canvas>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
 
          </div>
 
          </div>
 
          <div class="row mb-1">
<div class="col-md-12">
 
<div class="card card-success">
<div class="card-header">
<h5 class="card-title">Analyse Fourisseur</h5>
 
                <div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="chart">
<canvas id="supplierCostChartByMatieres" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
</div>
</div>
<!-- /.card-body -->
</div>
 
        </div>
 
        </div>
 
        </div>


<div id="FournisseursContent" class="tab-content" style="display: none;">
 
    <!-- <button class="btn btn-success" onclick="openWorkerModal()">+ Nouvel ouvrier</button> -->
    <br>
    <br>
    <div class="card-body table-responsive">

    <table  id="targetTable" class="table table-hover">
        <thead>
            <tr>
                <!-- <th>Fournisseur id</th> -->
                <th>Reseau social</th>
                <th>Nom contact</th>
                <th>Email</th>
                <th>Télephone</th>
                <th>Adresse</th>
                <th>Download</th>
            </tr>
        </thead>
        <tbody>
        @foreach($fournisseurs_affected  as $fournisseur)
<tr data-chantier-id="{{ $chantier->id }}" data-fournisseur-id="{{ $fournisseur->id }}" data-fournisseur-reseau="{{ $fournisseur->reseau_social }}">
    <!-- <td>{{ $fournisseur->id }}</td> -->
    <td>{{ $fournisseur->reseau_social }}</td>
    <td>{{ $fournisseur->nom_contact }}</td>
    <td>{{ $fournisseur->email }}</td>
    <td>{{ $fournisseur->telephone }}</td>
    <td>{{ $fournisseur->adresse }}</td>
    <td>
        <a href="/export-fournisseur-pdf?chid={{ $chantier->id }}&fornid={{ $fournisseur->id }}">
        <i class="far fa-file-pdf fa-2x"></i>
        </a>
&ensp;
        <a href="/send-welcome-email?chid={{ $chantier->id }}&fornid={{ $fournisseur->id }}">
        <i class="fas fa-share"></i>
        </a>
    </td>
 
</tr>
@endforeach
        </tbody>
    </table></div>
</div>
 <!-- final founis -->
      

 
<!-- Worker Modal -->
<div id="workerModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeWorkerModal();">&times;</span>
        <h5 style="text-align:center;"><b >Ajouter un nouvel ouvrier</b></h5>
       
        <!-- Worker form here -->
        <form id="addWorkerForm">
            @csrf
            <div class="form-group">
                <label for="workerSelect">Ouvrier</label>
                <select class="form-control" id="workerSelect" name="ouvrier_id">
                <option value="">choisie un ouvrier</option>
                @foreach($ouvriers as $ouvrier)
                
                  <option value="{{ $ouvrier->id }}">{{ $ouvrier->prenom }} {{ $ouvrier->nom }}</option>
              @endforeach
                </select>
            </div>
            <div class="form-group">
                <label for="dateDebut">Date de début</label>
                <input type="date" id="dateDebut" name="date_debut" class="form-control">
            </div>
            <div class="form-group">
                <label for="dateFin">Date de fin</label>
                <input type="date" id="dateFin" name="date_fin" class="form-control">
            </div>
            <input type="hidden" name="chantier_id" value="{{ $chantier->id }}">
            <button type="submit" class="btn btn-primary">Ajouter</button>
        </form>
    </div>
</div>
 
 
               
            </div>
        </div>
    </div>
</div>
 
</div>

<!-- ====== -->

<!-- Modal -->
<div class="modal fade" id="fournisseurModal" tabindex="-1" role="dialog" aria-labelledby="fournisseurModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="fournisseurModalLabel">Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>
        <b>Ste: <span id="modalFournisseurReseau"/></b></p>
        <p hidden>Chantier ID: <span id="modalChantierId">123</span> Fournisseur ID: <span id="modalFournisseurId">456</span></p>
        
        <!-- Table for Matière Première -->
        <table id="tablemat" class="table tablemat">
<!--           <thead>
            <tr>
              <th>Matière Première</th>
              <th>Quantité</th>
              <th>Prix Unitaire</th>
              <th>Prix Total</th>
            </tr>
          </thead> -->
          <tbody>
            
 
          </tbody>
        </table>

        <button type="button"  id="addPaiementButton" class="btn btn-primary" style="margin-bottom: 10px;">Add paiement</button>

        <!-- Table for Paiements -->
        <table id="table2fournisseur" class="table table2fournisseur">
<!--           <tbody>
            <tr>
              <td colspan="3" style="text-align: right;" ><strong>Total Paiement</strong></td>
              <td id="totalPaiement" style="font-weight: bold;"></td>
            </tr>
          </tbody> -->
        </table>
        <div id="resultDiv" class="result">
          <!-- This content will be set dynamically -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<!-- pop d tar7 -->

<!--  -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <div class="modal-content">
            <div class="modal-header">
            <h4 class="modal-title">détails du budget</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
               
            </div>
            <div class="modal-body"><center>
                <div style="font-weight:bold; font-family:Arial;">
                <?php
$table = '<table style="width:120px;text-align:center;background-color:white;"><tr><td style="width: 30px;"></td>'; // Set the width and alignment for the first td
$i = 0;
$result=$total_prix_estime-$pricet;
foreach ($articles_chantiers as $art) {
    if ($art->chantier_id == $chantier->id) {
        if($i == 0) {
            $table .= '<td>' . $art->prix_estime . '</td></tr>'; // Align left for the second td
        } else {
            $table .= '<tr><td style="width: 30px;">+</td><td>' . $art->prix_estime . '</td></tr>'; // Apply styles to both tds
        }
        $i++;
    }
}
$table .= '<tr  style="border-top: 2px solid #000; width:50%;"><th>=</th><th>'.$total_prix_estime.'DH</th></tr>';
$table .= '<tr><th>-</th><th>'. $pricet.'DH</th></tr>';
// $table .= '<tr style="border-top: 2px solid #000;><th></th><th></th></tr>';
// $table .= '<tr><th>=</th><th></th></tr>';
$table .= '<tr  style="border-top: 2px solid #000; "><th>=</th><th>'. $result.'</th></tr>';
$table .= '</table>';

echo($table);
?>


<div>
             @if ($result>=0)
        <span style="padding: 15px; color: #2ECC71; margin-bottom: -24px; border-bottom-right-radius: 3px;">
       <b> vous avez gagné : {{ $result }} DH</b></span>

    @else
        <span style="padding: 15px;color: red; margin-bottom: -24px; border-bottom-right-radius: 3px;">
        <b>vous avez perdu : {{ $result }} DH</b></span>
        @endif
                </div>

<!--  -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
document.getElementById('myBtn').onclick = function() {
    document.getElementById('expenseModal').style.display = "block";
}
document.addEventListener('DOMContentLoaded', (event) => {
    document.getElementsByClassName('close')[0].onclick = function() {
        document.getElementById('expenseModal').style.display = "none";
    };
 
    // Initialize the Articles grid
    var ArticleGrid = document.getElementById("ArticleGrid");
    var chantierId = "{{ $chantier->id }}"; // Assuming this is the current chantier ID
    var articles = @json($articles); // Your articles array
 
    articles.forEach(function(article) {
        var card = document.createElement("div");
        card.className = "card2";
        card.innerHTML = '<div class="Article-icon"><i class="fas fa-box"></i></div>' +
                         '<span>' + article.ref + '</span>';
        // Add an onclick event to the card
        card.onclick = function() {
            // Call function to add the article to the database
            addArticleToChantier(article.id, chantierId);
        };
        ArticleGrid.appendChild(card);
    });
});
 
function addArticleToChantier(articleId, chantierId) {
    $.ajax({
        url: '{{ route("chantiers.assignArticle") }}', // URL to the route handling the assignment
        type: 'POST',
        data: {
            _token: "{{ csrf_token() }}",
            article_id: articleId,
            chantier_id: chantierId
        },
        success: function(data) {
            if(data.success) {
                // If the insertion was successful, you might want to update the UI or notify the user
                alert('Article affecté avec succès');
                $('#expenseModal').modal('hide');
                location.reload();
            }
        },
        error: function(response) {
            // Handle errors here
            alert('An error occurred while adding the article');
        }
    });
}
 
// Other existing scripts...
 
 
// Generate Article cards
// Articles.forEach(function(Article) {
   
// });
 
$(document).ready(function() {
    $('#searchBox').on('keyup', function() {
        var value = $(this).val().toLowerCase();
        $("#ArticleGrid .card2").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
});
 
 
  $(document).ready(function() {
    $('#addArticleForm').submit(function(e) {
      e.preventDefault();
 
      $.ajax({
        url: '{{ route("chantiers.assignArticle") }}',
        type: 'POST',
        data: $(this).serialize(),
        success: function(data) {
          if(data.success) {
            $('#articleModal').modal('hide');
            // Refresh the articles list or show a success message
            alert('Article assigned successfully');
          }
        },
        error: function(response) {
          // Handle errors
          if(response.status === 409) {
            alert(response.responseJSON.error);
          } else {
            alert('An error occurred');
          }
        }
      });
    });
  });
 
  function openArticleModal() {
    $('#articleModal').modal('show');
  }
  function closeWorkerModal() {
    $('#workerModal').modal('hide');
}
// pour supprimer les article associe au chantier
// Function to delete an article assignment via AJAX
function deleteArticleAssignment(chantierId, articleId) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette affectation d\'article ?')) {
        return; // Stop if the user cancels the confirmation dialog.
    }

    $.ajax({
        url: `/chantier/${chantierId}/article/${articleId}`, // Adjust if you are using a different base URL
        type: 'DELETE',
        data: {
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        success: function(result) {
            // alert('L\'affectation de l\'article a été supprimée avec succès.');
            location.reload(); // Reload the page to see the changes
        },
        error: function(xhr, status, error) {
            alert('Une erreur est survenue lors de la suppression.');
        }
    });
}

// Attach the delete function to the click event of your delete buttons for articles
$(document).on('click', '.delete-article-btn', function(e) {
    e.preventDefault();
    var chantierId = $(this).data('chantier-id');
    var articleId = $(this).data('article-id');
    deleteArticleAssignment(chantierId, articleId);
});

// 
</script>
 
<!-- ouvrier -->
<script type="text/javascript">
  function openWorkerModal() {
    $('#workerModal').modal('show');
  }
 
  $('#addWorkerForm').submit(function(e) {
  e.preventDefault();
 
  $.ajax({
    url: '{{ route("chantiers.assignWorker") }}', // Ensure this route is defined in your web.php
    type: 'POST',
    data: $(this).serialize(),
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // Ensure CSRF token is being sent
    },
    success: function(data) {
      if(data.success) {
       
        alert('Ouvrier affecté avec succès');
        $('#workerModal').modal('hide');
        location.reload();
        // Optionally refresh part of your page to show the new worker
      }
    },
    error: function(response) {
            // Handle errors traduction des erreur...
            if (response.status === 422) { // Validation error status code
                var errors = response.responseJSON.errors;
                var errorMessages = [];
                for (var key in errors) {
                    if (errors.hasOwnProperty(key)) {
                        errorMessages.push(errors[key][0]);
                    }
                }
                alert(errorMessages.join("\n"));
            }// Handle 409 conflict errors
    else if (response.status === 409) {
        var errorMessage = response.responseJSON.error;
        alert(errorMessage);
    }
    // Handle other errors
    else {
        alert('Une erreur est survenue lors de la tentative d\'affectation.');
    }
        }
    });
});
// 
 // Function to delete a worker assignment via AJAX
 function deleteWorkerAssignment(chantierId, ouvrierId) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette affectation ?')) {
      return; // Stop if the user cancels the confirmation dialog.
    }

    $.ajax({
      url: `/chantier/${chantierId}/ouvrier/${ouvrierId}`,
      type: 'DELETE',
      data: {
        _token: $('meta[name="csrf-token"]').attr('content')
      },
      success: function(result) {
        alert('L\'affectation de l\'ouvrier a été supprimée avec succès.');
        location.reload(); // Reload the page to see the changes
      },
      error: function(xhr, status, error) {
        alert('Une erreur est survenue lors de la suppression.');
      }
    });
  }

  // Attach the delete function to the click event of your delete buttons
  $(document).on('click', '.delete-worker-btn', function(e) {
    e.preventDefault();
    var chantierId = $(this).data('chantier-id');
    var ouvrierId = $(this).data('ouvrier-id');
    deleteWorkerAssignment(chantierId, ouvrierId);
  });
// 
$(document).ready(function(){
  // Function to show a tab navigation show/hide/ rederiction
  function showTab(tabId) {
    $('.nav-link').removeClass('active');
    $('.tab-content').hide();
    $(tabId).show();
    $('a[data-target="' + tabId + '"]').addClass('active');
  }
 
  // Check for a saved tab in localStorage
  var activeTab = localStorage.getItem('activeTab');
  if (activeTab) {
    showTab(activeTab);
  } else {
    // Default to showing the first tab if none is saved
    showTab('#defaultTabId'); // Replace '#defaultTabId' with the ID of your default tab
  }
 
  // Update the active tab on click and save it to localStorage
  $('.nav-link').click(function(e) {
    e.preventDefault();
    var selectedTab = $(this).data('target');
    localStorage.setItem('activeTab', selectedTab);
    showTab(selectedTab);
  });});
 
 
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function(){
    // Other tab-related scripts...
 
    // Define the bar chart for sales over time
    // var ctxBar = document.getElementById('salesBarChart').getContext('2d');
    // var salesBarChart = new Chart(ctxBar, {
    //     type: 'bar',
    //     data: {
    //       labels: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin'],
    //         datasets: [{
    //             label: 'Vente',
    //             data: [1500, 2000, 1800, 2200, 1900, 2100],
    //             backgroundColor: 'rgba(54, 162, 235, 0.2)',
    //             borderColor: 'rgba(54, 162, 235, 1)',
    //             borderWidth: 1
    //         }]
    //     },
    //     options: {
    //         scales: {
    //             y: {
    //                 beginAtZero: true
    //             }
    //         }
    //     }
    // });

    <?php
$labels = [];
$data = [];
$backgroundColor = [];
$backgroundColor_art=[];

foreach($articles_chantiers as $art) {
    foreach($articles as $arti) {
        if($arti->id == $art->article_id&&$art->chantier_id==$chantier->id) {
            $labels[] = $arti->ref; 
            $color='rgba(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
            $backgroundColor[] =  $color. ', 0.2)';
            $backgroundColor_art[] = $color. ', 1)';     
          
    
    
    $pricet = 0;
    foreach($ch_ar_mt_fr as $row) {
        if($row->article_chantier_id == $art->id) {
            $pricet += $row->prix * $row->qte;
        }
    }
    
    
    $data[] = $pricet;
}
    // Generate a random color for each label
}}//
?>

// Define the pie chart for sales distribution
var ctxPie = document.getElementById('salesPieChart').getContext('2d');
var salesPieChart = new Chart(ctxPie, {
    type: 'pie',
    data: {
        labels: <?php echo json_encode($labels); ?>,
        datasets: [{
            label: 'Prix Distribution',
            data: <?php echo json_encode($data); ?>,
            backgroundColor: <?php echo json_encode($backgroundColor); ?>,
            borderColor:<?php echo json_encode($backgroundColor_art); ?>,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});




<?php

$labels_ouvrier = [];
$data_ouvrier = [];
$backgroundColor_ouvrier = [];
$border_ouvrier=[];
foreach($ouvrier_chantiers as $ouvrier_chantier){
    $labels_ouvrier[]=$ouvrier_chantier->nom;
    $startDate = \Carbon\Carbon::parse($ouvrier_chantier->pivot->date_debut);
    $endDate = \Carbon\Carbon::parse($ouvrier_chantier->pivot->date_fin);
    $daysWorked = $endDate->diffInDays($startDate);
    $totalPrice = $daysWorked * $ouvrier_chantier->salaire_journalier;
    $data_ouvrier[]= $totalPrice;
    $color='rgba(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
    $backgroundColor_ouvrier[] =  $color . ', 0.2)';
    $border_ouvrier[]=  $color. ', 1)';
}


?>

// Define the pie chart for sales distribution
var ctxPie = document.getElementById('OuvriersChart').getContext('2d');
var salesPieChart = new Chart(ctxPie, {
    type: 'pie',
    data: {
        labels: <?php echo json_encode($labels_ouvrier); ?>,
        datasets: [{
            label: 'Salaire Ouvriers',
            data: <?php echo json_encode($data_ouvrier); ?>,
            backgroundColor: <?php echo json_encode($backgroundColor_ouvrier); ?>,
            borderColor: <?php echo json_encode($border_ouvrier); ?>,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});



<?php

$labels_fornis = [];
$data_fornis = [];
$backgroundColor_fornis = [];

$totalPriceByFournisseur = [];
$borderColors_fornis  = [];

foreach($articles_chantiers as $art) {
    foreach($ch_ar_mt_fr as $row) {
        if($row->article_chantier_id == $art->id && $art->chantier_id==$chantier->id) {
            $fournisseurId = $row->fournisseur_id;
            $fournisseurName = $fournisseurs->firstWhere('id', $fournisseurId)->reseau_social ?? 'N/A';
            $totalPrice = $row->prix * $row->qte;

            // Check if the fournisseur is already in the array
            if (!array_key_exists($fournisseurName, $totalPriceByFournisseur)) {
                $totalPriceByFournisseur[$fournisseurName] = 0;
                $color='rgba(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
                $backgroundColor_fornis[$fournisseurName] =  $color. ', 0.2)';
                $borderColors_fornis[$fournisseurName] = $color. ', 1)';
            }
            $totalPriceByFournisseur[$fournisseurName] += $totalPrice;
        }
    }
}

// Now, populate the labels and data for the chart
foreach ($totalPriceByFournisseur as $fournisseurName => $totalPrice) {
    $labels_fornis[] = $fournisseurName;
    $data_fornis[] = $totalPrice;
}

?>

// Define the pie chart for sales distribution
var ctxPie = document.getElementById('FornisseursChart').getContext('2d');
var salesPieChart = new Chart(ctxPie, {
    type: 'pie',
    data: {
        labels: <?php echo json_encode($labels_fornis); ?>,
        datasets: [{
            label: 'Total price for each Fournisseur',
            data: <?php echo json_encode($data_fornis); ?>,
            backgroundColor: <?php echo json_encode(array_values($backgroundColor_fornis)); ?>, // Ensure colors match the labels
            borderColor: <?php echo json_encode(array_values($borderColors_fornis)); ?>,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});




<?php

$totalExpenditurePerSupplier = [];
foreach ($ch_ar_mt_fr as $row) {
foreach ($articles_chantiers as $art) {
        if ($row->article_chantier_id == $art->id&& $art->chantier_id==$chantier->id) {
            foreach ($matieres as $matiere) {
                if($matiere->id==$row->matierepremiere_id){
            if (!isset($totalExpenditurePerSupplier[$matiere->designation])) {
                $totalExpenditurePerSupplier[$matiere->designation] = 0;
                $color='rgba(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
                $backgroundColors[] =  $color. ', 0.2)';
                $borderColors[] = $color. ', 1)';
            }
            $totalExpenditurePerSupplier[$matiere->designation] += $row->prix * $row->qte; // price * quantity
        }}
        }
    }
}

$labels = array_keys($totalExpenditurePerSupplier);
$data = array_values($totalExpenditurePerSupplier);

// Assuming $totalExpenditurePerSupplier is your dataset prepared earlier

// Define color arrays

// Assuming $totalExpenditurePerSupplier contains your data
$labels = array_keys($totalExpenditurePerSupplier);
$data = array_values($totalExpenditurePerSupplier);

// Cycling through colors directly
$finalBackgroundColors = [];
$finalBorderColors = [];
foreach ($data as $index => $value) {
    $finalBackgroundColors[] = $backgroundColors[$index % count($backgroundColors)];
    $finalBorderColors[] = $borderColors[$index % count($borderColors)];
}
?>

// Define the pie chart for sales distribution
var ctx = document.getElementById('expenditurePerSupplierChart').getContext('2d');
    var expenditurePerSupplierChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: <?php echo json_encode($labels); ?>,
            datasets: [{
                data: <?php echo json_encode($data); ?>,
                backgroundColor: <?php echo json_encode($finalBackgroundColors)?>,
                borderColor: <?php echo json_encode($finalBorderColors)?>,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: false,
                text: 'Total Expenditure Per Supplier'
            }
        }
    });



    <?php
// Assuming $matieres is a list of all "Matière Première".
// Assuming $fournisseurs is a list of all "Fournisseur".

// Initialize the arrays to store labels and datasets
$matiereLabels = []; // To store "Matière Première" names
$datasets = []; // To store the datasets for each "Fournisseur"
$backgroundColor = []; // To store background colors for the chart

// Prepare the dataset for each "Fournisseur"
foreach ($ch_ar_mt_fr as $row) {
    foreach ($articles_chantiers as $art) {
        if ($row->article_chantier_id == $art->id && $art->chantier_id == $chantier->id) {
            foreach ($fournisseurs as $fournisseur) {
                if ($row->fournisseur_id == $fournisseur->id) {
                    $color='rgba(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255);
                    $datasets[$fournisseur->id] = [
                        'label' => $fournisseur->reseau_social,
                        'backgroundColor' => $color . ', 0.6)',
                        'borderColor' => $color . ', 1)',
                        'data' => []
                    ];
                    // $datasets[$fournisseur->id]['data'][] = 0; // Initialize with zero
                }
            }
        }
    }
}

// Populate the datasets with expenditure data per "Matière Première"
// foreach ($ch_ar_mt_fr as $row) {
//     foreach ($articles_chantiers as $art) {
//         if ($art->id == $row->article_chantier_id && $art->chantier_id == $chantier->id) {
//             foreach ($matieres as $matiere) {
//                 if ($row->matierepremiere_id == $matiere->id) {
//                     // Add the "Matière Première" name to the labels array only if it's unique
//                         $matiereLabels[] = $matiere->designation;
//              }
//             }
//         }
//     }
// }

foreach ($ch_ar_mt_fr as $row) {
    foreach ($articles_chantiers as $art) {
        if ($row->article_chantier_id == $art->id && $art->chantier_id == $chantier->id) {
            foreach ($fournisseurs as $fournisseur) {
                if ($row->fournisseur_id == $fournisseur->id) {
                    foreach ($matieres as $matiere) {
                        if ($row->matierepremiere_id == $matiere->id) {

                            // if (!in_array($matiere->designation, $matiereLabels)) {
                            //     $matiereLabels[] = $matiere->designation;
                            // }
                        // if(!$datasets[$row->fournisseur_id]['data'][$matiere->designation])
                        // $datasets[$row->fournisseur_id]['data'][$matiere->designation]=0;
                        if (!isset($datasets[$row->fournisseur_id]['data'][$matiere->designation])) {
                            $datasets[$row->fournisseur_id]['data'][$matiere->designation] = 0;
                        }
                        $datasets[$row->fournisseur_id]['data'][$matiere->designation] += $row->prix * $row->qte;                }}
                }
            }
        }
    }
}

// Convert datasets to a zero-indexed array
$finalDatasets = array_values($datasets);

// Make sure the "Matière Première" names are unique
$matiereLabels = array_unique($matiereLabels);
?>

var ctx = document.getElementById('supplierCostChartByMatieres').getContext('2d');
var matierePremiereBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?php echo json_encode($matiereLabels); ?>,
        datasets: <?php echo json_encode($finalDatasets); ?>
    },
    options: {
        indexAxis: 'x', // Horizontal chart
        scales: {
            x: {
                stacked: true, // Required for the stacked bar chart
            },
            y: {
                stacked: true, // Required for the stacked bar chart
            }
        },
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top', // Position of "Fournisseur" legend
            }
        }
    }
});
 
var canvas = document.getElementById('supplierCostChartByMatieres');
canvas.addEventListener('mouseover', function(event){
  event.preventDefault();
  // Rest of your mouseover logic
});




});
</script>
 <!-- added -->
 <script>
    $(document).ready(function() {  
    // ... (rest of your existing script)

    // AJAX call for deletion
    $(document).on('click', '.delete-matiere-btn', function() {
        if(!confirm('Are you sure you want to delete this matiere?')) {
            return;
        }

        var id = $(this).data('id');
        var token = $('meta[name="csrf-token"]').attr('content');

        $.ajax({
            url: `/matieres/${id}`, // Change this URL to the route that handles deletion
            type: 'DELETE',
            data: {
                _token: token,
                id: id
            },  
            success: function(response) {
                alert('Matiere deleted successfully');
                location.reload(); // Reloads the page to update the table
            },
            error: function(jqXHR) {
                console.error('AJAX Error:', jqXHR.responseText);
                alert('AJAX Error: ' + jqXHR.responseText);
            }
        });
    });

    // ... (rest of your existing script)
    


  // Example function to open the modal (You'll need to replace this with your actual function)
  $('tbody').on('click', '.view-article-btn', function() {
  // Show the modal
  $('#materialModal').modal('show');

  // Retrieve the 'article_id' from the data attribute of the clicked button
 
        var articleChantierId = $(this).data('article-chantier-id');

        var articleId = articleChantierId;


  // Log the article ID to the console
  console.log(articleChantierId);

  // Convert the PHP array to a JavaScript array
  var ch_ar_mt_fr = <?php echo json_encode($ch_ar_mt_fr); ?>;
  console.log(ch_ar_mt_fr);

  var articlechantierjr = <?php echo json_encode($arts); ?>;
  var chatiersjr = <?php echo json_encode($chantier); ?>;
  var fournisseurjs = <?php echo json_encode($fournisseurs); ?>;
  var matiersjs = <?php echo json_encode($matieres); ?>;

  // Initialize an empty string for the table rows
  var stringdata = '';
  console.log(articlechantierjr);
  console.log(chatiersjr["id"]);

  for (var i = 0; i < ch_ar_mt_fr.length; i++) {
    var row = ch_ar_mt_fr[i];
    // for (var a = 0; a < articlechantierjr.length; a++) {
    //     if(articlechantierjr[a]["pivot"]["chantier_id"]==chatiersjr["id"]&& articlechantierjr[a]["pivot"]["article_id"]==articleId){

    

    if (row.article_chantier_id == articleId) {
        
        for (var j = 0; j < fournisseurjs.length; j++) {
            var row2 = fournisseurjs[j];
            if (row2.id == row.fournisseur_id) {
        for (var k = 0; k < matiersjs.length; k++) {
            var row3 = matiersjs[k];
            if (row3.id == row.matierepremiere_id) {
            // console.log(row2);  '<td>' + (row["article_chantier_id"]) + '</td>' +

      stringdata += '<tr>' +
        '<td>' + (row3["designation"] ) + '</td>' +
        '<td>' + (row2["reseau_social"]) + '</td>' +
        '<td>' + row["num_bon"] + '</td>' +
        '<td>' + row["qte"] + '</td>' +
        '<td>' + row["unite"] + '</td>' +
        '<td>' + row["prix"] + '</td>' +
        '<td>' +
        '<button type="button" class="btn btn-danger delete-matiere-btn" data-id="' + row["id"] + '">' +  // Assuming row.id is the primary key of the matiere
        '<i class="fas fa-trash-alt"></i>' +
        '</button>' +
        '</td>' +
        '</tr>';
    }}}
  }}
}
// }
// }

  // Append the rows to the table
  $('#materialsTable tbody').empty();

  $('#materialsTable tbody').append(stringdata);







// Options for matieres and fournisseurs, assuming these are predefined or set elsewhere
var matieresOptions = `@foreach ($matieres as $matiere)
                              <option value="{{ $matiere->id }}">{{ $matiere->designation }}</option>
                           @endforeach`;

    var fournisseursOptions = `@foreach ($fournisseurs as $fournisseur)
                                  <option value="{{ $fournisseur->id }}">{{ $fournisseur->reseau_social }}</option>
                               @endforeach`;

    // Add new material row
    $('#addNewMaterial').click(function() {
        // var articleId = $('#addMaterialForm input[name="article_id"]').val(); // Ensure you have a method to set this
        var newRow = stringdata+`<tr><input type="hidden" class="form-control" name="article_chantier_id" value="${articleId}">
                        
                        <td><select class="form-control" name="matierepremiere_id">${matieresOptions}</select></td>
                        <td><select class="form-control" name="fournisseur_id">${fournisseursOptions}</select></td>
                        <td><input type="text" class="form-control" name="num_bon"></td>
                        <td><input type="number" class="form-control" name="qte" step="0.5"></td>
                        <td><input type="text" class="form-control" name="unite"></td>
                        <td><input type="number" class="form-control" name="prix" step="0.5"></td>
                        <td><button type="button" class="btn btn-success submitMaterial">OK</button></td>
                      </tr>`;
        $('#materialsTable tbody').empty();
        $('#materialsTable tbody').append(newRow);
    });

    // Handle form submission via AJAX
    $(document).on('click', '.submitMaterial', function() {
        var row = $(this).closest('tr');
        var data = {
            article_chantier_id: row.find('input[name="article_chantier_id"]').val(),
            matierepremiere_id: row.find('select[name="matierepremiere_id"]').val(),
            fournisseur_id: row.find('select[name="fournisseur_id"]').val(),
            num_bon: row.find('input[name="num_bon"]').val(),
            qte: row.find('input[name="qte"]').val(),
            unite: row.find('input[name="unite"]').val(),
            prix: row.find('input[name="prix"]').val(),
            _token: $('meta[name="csrf-token"]').attr('content') // Ensure CSRF token meta tag is in the head
        };

        $.ajax({
            url: '/chantiers/add-material', // Adjust if necessary
            type: 'POST',
            data: data,
            success: function(response) {
                
                $('#materialModal').modal('hide'); // Cacher la pop-up
                $('#materialsTable tbody').empty();
                alert('Material added successfully');
                location.reload();
                


                // Optionally clear the form or close the modal here
            },
            error: function(jqXHR, textStatus, errorThrown) {
    console.error('AJAX Error:', textStatus, errorThrown);
    console.error('Response Text:', jqXHR.responseText);
    alert('AJAX Error: ' + jqXHR.responseText);
}
        });
    });});
});
// bax nsedha
  function closeMatiereModal() {
    $('#materialModal').modal('hide');
    $('#materialsTable tbody').empty();
}
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var fournisseurId=null;
    var chantierId= null;
    var rows = document.querySelectorAll('#targetTable tbody tr');
    rows.forEach(function(row) {
        row.addEventListener('dblclick', function() {
             chantierId = this.getAttribute('data-chantier-id');
             fournisseurId = this.getAttribute('data-fournisseur-id');
            var fournisseurReseau = this.getAttribute('data-fournisseur-reseau');
            // alert(fournisseurId);
            
            // These PHP variables should be converted to JSON in the PHP script, not here
            var matieres = <?php echo json_encode($matieres); ?>;
            var fournisseurs = <?php echo json_encode($fournisseurs); ?>;
            var articles_chantiers = <?php echo json_encode($articles_chantiers); ?>;
            var ch_ar_mt_fr = <?php echo json_encode($ch_ar_mt_fr); ?>;
            var matierepremiere = <?php echo json_encode($matieres); ?>;
            
            // Set the IDs in the modal
            document.getElementById('modalChantierId').textContent = chantierId;
            document.getElementById('modalFournisseurId').textContent = fournisseurId;
            document.getElementById('modalFournisseurReseau').textContent = fournisseurReseau;

            var prix_total = 0;
            var table = document.querySelector("#fournisseurModal .tablemat"); // Your table selector
            $('#tablemat').empty();
            $('#tablemat').append('<thead><tr><th>Matière Première</th><th>Quantité</th><th>Prix Unitaire</th><th>Prix Total</th></tr></thead>');

            // Clear existing rows
            // table.innerHTML = '';

            // Loop through articles_chantiers and ch_ar_mt_fr to fill the table
            articles_chantiers.forEach(function(artchat) {
                ch_ar_mt_fr.forEach(function(row) {
                    if (artchat.chantier_id == chantierId && row.fournisseur_id == fournisseurId && row.article_chantier_id == artchat.id) {
                        var totalLigne = row.qte * row.prix;
                        prix_total += totalLigne;

                        // Create a new row and cells
                        var newRow = table.insertRow(table.rows.length);
                        matierepremiere.forEach(function(matiere) {
                            if (matiere.id == row.matierepremiere_id) {
                                newRow.insertCell(0).textContent = matiere.designation;
                                newRow.insertCell(1).textContent = row.qte;
                                newRow.insertCell(2).textContent = row.prix;
                                newRow.insertCell(3).textContent = totalLigne + ' DH';
                            }
                        });
                    }
                });
            });

                 var newRow = table.insertRow(-1); // Add at the end of the table
                var cell = newRow.insertCell(0);
                cell.colSpan = 3;
                cell.style.textAlign = "right";
                newRow.style.fontWeight = "bold";
                cell.className ="totalMatiere";
                cell.id="totalMatiere";
                cell.textContent = "Total Prix des Matières";
                newRow.insertCell(1).textContent = prix_total + ' DH';



var reglements = <?php echo json_encode($Reglements); ?>;
var modereglements = <?php echo json_encode($ModeReglements); ?>;
var table2 = document.querySelector("#fournisseurModal .table2fournisseur"); // Your table selector
$("#table2fournisseur").empty();
$("#table2fournisseur").append('<thead><tr><th>Date</th><th>Mode de Paiement</th><th>Numero cheque</th><th>Montant</th><th>Valide</th></tr></thead>');

var totalpaye=0; 
reglements.forEach(function(reg) {
    modereglements.forEach(function(modereglement) {
        if (reg.fournisseur_id == fournisseurId && reg.chantier_id == chantierId && reg.mode_id ==modereglement.id ) {

            // Create a new row and cells
            var newRow = table2.insertRow(table2.rows.length);
            newRow.insertCell(0).textContent = reg.date;
            newRow.insertCell(1).textContent = modereglement.mode;
            newRow.insertCell(2).textContent = reg.num_cheque;

            newRow.insertCell(3).textContent = reg.montant;
            newRow.insertCell(4).innerHTML = '<i style="color: green; padding-left: 20px; font-size: 20px;" class="fas fa-check"></i>';
            totalpaye=totalpaye+reg.montant;
        }
    });
});
// <i style="color: green; padding-left:20px;" class="fas fa-chart-line"></i>

                 var newRow = table2.insertRow(-1); // Add at the end of the table
                var cell = newRow.insertCell(0);
                cell.colSpan = 4;
                cell.style.textAlign = "right";
                newRow.style.fontWeight = "bold";
                cell.className ="totalPaiement";
                cell.id ="totalPaiement";
                cell.textContent = "Total Paiement";
                newRow.insertCell(1).textContent = totalpaye + ' DH';
function updateResult() {
    var totalMatiere =prix_total ;
    var totalPaiement = totalpaye;
    var resultDiv = document.getElementById('resultDiv');
    var result=totalMatiere-totalPaiement;
    // alert(totalMatiere);
    
    if (totalMatiere <= totalPaiement) {
      resultDiv.className = 'result positive-result'; // Adds green background
      resultDiv.textContent = 'Reste a rendre: ' + Math.abs(result)   + ' DH';
    } else {
      resultDiv.className = 'result negative-result'; // Adds red background
      resultDiv.textContent = 'Reste a paye: ' + Math.abs(result)   + ' DH';
    }
  }
    updateResult();

  
  



            // Show the modal
            // If using Bootstrap 5 and vanilla JS:
            var modal = new bootstrap.Modal(document.getElementById('fournisseurModal'));
            modal.show();


            // If using Bootstrap 4 and jQuery:
            // $('#fournisseurModal').modal('show');
        });
    });




  // Reference to the "Add paiement" button
  var addPaiementButton = document.getElementById('addPaiementButton');
  
  // Function to add a new payment row
  function addPaiementRow() {
    var table = document.querySelector("#fournisseurModal .table2fournisseur"); // Your table selector
    if (table.querySelector("input, select")) {
        // prompt(" Veuillez compléter l'entrée de paiement existante avant d'en ajouter une nouvelle.");
        return; // Exit the function, do not add a new row
    }
    var lastRowIndex = table.rows.length - 1; // Index of the last row
    var newRow = table.insertRow(lastRowIndex);
    // var newRow = table.insertRow(); // Insert a new row

    // Insert cells (`td`) into the new row
    var newCellDate = newRow.insertCell(0);
    var newCellMode = newRow.insertCell(1);
    var newCellNumcheque = newRow.insertCell(2);
    var newCellValide = newRow.insertCell(3);
    var newCellMontant = newRow.insertCell(4);

    // Populate the Date cell with an input field
    newCellDate.innerHTML = '<input required type="date" class="form-control">';
        var options = <?php echo json_encode($ModeReglements); ?>;
        var selectHTML = '<select required class="form-control">';
        options.forEach(function(option) {
            selectHTML += `<option value="${option.id}">${option.mode}</option>`;
        });
        selectHTML += '</select>';
        newCellMode.innerHTML = selectHTML;
    // Populate the Valide cell with an input field
    // newCellValide.innerHTML = '<input type="number" required step=0.5 class="form-control">';
    console.log(chantierId, fournisseurId);
    // Add the insert button to the Montant cell
    newCellNumcheque.innerHTML = '<input type="number" required step=0.5 class="form-control">';

    newCellValide.innerHTML = '<input type="number" required step=0.6 class="form-control">';
    console.log(chantierId, fournisseurId);
    // Add the insert button to the Montant cell
    newCellMontant.innerHTML = `<td><button class="btn btn-success" data-chantier-id="chantierId",data-fournisseur-id="fournisseurId" onclick="insertPaiement(this, '${chantierId}', '${fournisseurId}')">Payé</button></td>`;
}

// Add click event listener to the "Add paiement" button
addPaiementButton.addEventListener('click', addPaiementRow);

});
function insertPaiement(button, chantierId, fournisseurId) {
    var row = button.parentElement.parentElement;
    var date = row.cells[0].querySelector('input').value;
    var mode = row.cells[1].querySelector('select').value;
    var num_cheque = row.cells[2].querySelector('input').value;
    var montant = row.cells[3].querySelector('input').value;
    console.log(chantierId,fournisseurId,date,mode,num_cheque,montant);

    $.ajax({
        url: '/insert-payment',
        type: 'POST',
        data: {
            chantier_id: chantierId,
            fournisseur_id: fournisseurId,
            date: date,
            mode_id: mode,
            num_cheque:num_cheque,
            montant: montant
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            alert('Payment successfully inserted');
            location.reload();
        },
        error: function(xhr, status, error) {
            alert('Error inserting payment: ' + xhr.responseText);
        }
    });
}
</script>



 <!-- jQuery first, then Popper.js, then Bootstrap JS -->
<!-- <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> -->
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>-->

<script>
$(document).ready(function() {
    // Collapse functionality
    $('.btn-tool[data-card-widget="collapse"]').click(function() {
        var cardBody = $(this).closest('.card').find('.card-body');
        cardBody.toggle();
        $(this).children('i').toggleClass('fas fa-minus fas fa-plus');
    });
 
    // Remove functionality
    $('.btn-tool[data-card-widget="remove"]').click(function() {
        $(this).closest('.card').remove();
    });
});
</script>
<!-- <script>
$(document).ready(function(){
    $("#detail_chantier").click(function(){
        $("#myModal").modal('show');
    });
});
</script> -->
<script>
$(document).on('click', '.edit-article-btn', function(e) {
    e.preventDefault();
    var articleChantierId = $(this).data('article-chantier-id');
    var currentPrice = $(this).data('current-price');
    var newPrice = prompt("Entrez le nouveau prix estimé:", currentPrice);
    if (newPrice !== null && newPrice !== currentPrice) {
        $.ajax({
            url: `/article-chantier/${articleChantierId}/update-price`,
            type: 'POST',
            data: {
                prix_estime: newPrice,
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'PUT'
            },
            success: function(result) {
                alert('Le prix estimé a été mis à jour avec succès.');
                location.reload(); // Reload the page to see the updated price
            },
            error: function(xhr, status, error) {
                alert('Erreur lors de la mise à jour du prix estimé.');
            }
        });
    }
});
</script>
<script>
$(document).ready(function(){
    $("#detail_chantier").click(function(){
        $("#myModal").modal('show');
    });
});
</script>
</body>
</html>